【问题标题】:Spring Boot 2: IntegrationTest should not execute CommandLineRunner implSpring Boot 2:IntegrationTest 不应执行 CommandLineRunner impl
【发布时间】: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 类中。但是不应在测试用例中调用此执行。我怎样才能做到这一点?

谢谢:)

【问题讨论】:

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


【解决方案1】:

添加到SurveyRestServiceTest

@SpringBootTest(classes = Application.class)

【讨论】:

  • 感谢您的回复。 Hello worldApplication 类中的标准输出)在日志中仍然可见:(因此我的生产代码将在测试期间执行。
最近更新 更多