【发布时间】:2019-03-21 16:56:32
【问题描述】:
我不明白:Application 代码是在我的集成测试期间执行的。
这是我的Application 课程:
@SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Autowired
SurveyService surveyService;
@Override
public void run(String... args) throws Exception {
System.out.println("Hello world");
// some useage of the autowired service (do all the stuff)
}
}
SurveyService 只使用一些 REST API。
我的测试看起来像这样:
@ExtendWith(SpringExtension.class)
@RestClientTest({SurveyRestService.class})
@ComponentScan("com.example.app")
@TestPropertySource(properties = "uri=http://testMe.com/")
class SurveyRestServiceTest {
@Autowired
SurveyService classUnderTest;
@Autowired
MockRestServiceServer mockServer;
private void setupMockServerAndRespond(String response) {
mockServer.expect(requestTo("http://testMe.com/surveys")).andRespond(withSuccess(response, APPLICATION_JSON));
}
@Test
void shouldDeserialzeAllFields() {
setupMockServerAndRespond(VALID_JSON_ONE_ENTRY);
List<Survey> surveys = classUnderTest.listSurveys();
assertThat(surveys).hasSize(1);
// ...
}
}
如果我执行测试,我总是会看到 Hello world(参见 Application 类)。为什么会执行Application 代码?当我远程调用SpringApplication.run 时,它也执行了。
在生产模式下,我的应用应该启动,执行一些 REST 调用然后终止。所以我把所有的处决都放在我的Application 类中。但是不应在测试用例中调用此执行。我怎样才能做到这一点?
谢谢:)
【问题讨论】:
-
找到解决方案(使用 Profiles),请参阅:*.com/a/35098172/5012221
标签: java spring-boot testing spring-boot-test