Spring Boot 2:IntegrationTest不应该执行CommandLineRunner impl

时间:2018-10-17 05:10:47

标签: java spring-boot testing spring-boot-test

我不明白: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调用时,它也会执行。

在生产模式下,我的App应该启动,执行一些REST调用,然后终止。因此,我将所有执行都放在我的Application类中。但是,这种执行不应在测试用例中调用。我该如何实现?

谢谢:)

1 个答案:

答案 0 :(得分:0)

添加到SurveyRestServiceTest中:

@SpringBootTest(classes = Application.class)