文档中有一章很好的章节,建议您通读它以完全理解您可以做什么。
我喜欢使用
@IntegrationTest自定义配置,因为它可以启动整个服务器并允许您测试整个系统。如果要用模拟替换系统的某些部分,可以通过排除某些配置或bean并用自己的替换来实现。
这是一个小例子。我省略了该
MessageService接口,因为它从功能上显而易见
IndexController,并且是默认实现
DefaultMessageService--因为它不相关。
它的作用是将整个应用程序减至最小,
DefaultMessageService但将其自身
MessageService保留。然后,它
RestTemplate用于在测试用例中向正在运行的应用程序发出实际的HTTP请求。
应用类别:
IntegrationTestDemo.java:
@SpringBootApplicationpublic class IntegrationTestDemo { public static void main(String[] args) { SpringApplication.run(IntegrationTestDemo.class, args); }}IndexController.java:
@RestControllerpublic class IndexController { @Autowired MessageService messageService; @RequestMapping("/") String getMessage() { return messageService.getMessage(); }}测试类别:
IntegrationTestDemoTest.java:
@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = TestConfig.class)@WebIntegrationTest // This will start the server on a random portpublic class IntegrationTestDemoTest { // This will hold the port number the server was started on @Value("${local.server.port}") int port; final RestTemplate template = new RestTemplate(); @Test public void testGetMessage() { String message = template.getForObject("http://localhost:" + port + "/", String.class); Assert.assertEquals("This is a test message", message); }}TestConfig.java:
@SpringBootApplication@ComponentScan( excludeFilters = { // Exclude the default message service @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = DefaultMessageService.class), // Exclude the default boot application or it's // @ComponentScan will pull in the default message service @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = IntegrationTestDemo.class) })public class TestConfig { @Bean // Define our own test message service MessageService mockMessageService() { return new MessageService() { @Override public String getMessage() { return "This is a test message"; } }; }}


