spring-boot testing – 多个测试可以共享一个上下文吗?
我创建了多个spring-boot测试类, (使用spring-boot
1.4.0 ) 。
FirstActionTest.java :
@RunWith(SpringRunner.class) @WebMvcTest(FirstAction.class) @TestPropertySource("classpath:test-application.properties") public class FirstActionTest { @Autowired private MockMvc mvc; // ... }
SecondActionTest.java :
@RunWith(SpringRunner.class) @WebMvcTest(SecondAction.class) @TestPropertySource("classpath:test-application.properties") public class SecondActionTest { @Autowired private MockMvc mvc; // ... }
运行测试时:
mvn测试
它似乎为每个测试类创建了一个弹簧测试上下文,我猜这是不必要的。
问题是:
- 是否可以在多个测试类之间共享一个弹簧测试上下文,如果是,如何?
通过使用两个不同的类与@WebMvcTest
(即@WebMvcTest(FirstAction.class)
和@WebMvcTest(SecondAction.class)
),您明确指出您需要不同的应用程序上下文。 在这种情况下,您不能共享单个上下文,因为每个上下文包含一组不同的bean。 如果你的控制器bean表现得相当好,那么上下文应该相对快速地创建,你应该没有问题。
如果您确实希望在所有Web测试中都有一个可以缓存和共享的上下文,那么您需要确保它包含完全相同的bean定义。 我想到两个选择:
1) @WebMvcTest
没有指定任何控制器的情况下使用@WebMvcTest
。
FirstActionTest:
@RunWith(SpringRunner.class) @WebMvcTest @TestPropertySource("classpath:test-application.properties") public class FirstActionTest { @Autowired private MockMvc mvc; // ... }
SecondActionTest:
@RunWith(SpringRunner.class) @WebMvcTest @TestPropertySource("classpath:test-application.properties") public class SecondActionTest { @Autowired private MockMvc mvc; // ... }
2)根本不要使用@WebMvcTest
,以便获得包含所有bean的应用程序上下文(不仅仅是Web问题)
FirstActionTest:
@RunWith(SpringRunner.class) @SpringBootTest @TestPropertySource("classpath:test-application.properties") public class FirstActionTest { @Autowired private MockMvc mvc; // use MockMvcBuilders.webAppContextSetup to create mvc // ... }
SecondActionTest:
@RunWith(SpringRunner.class) @SpringBootTest @TestPropertySource("classpath:test-application.properties") public class SecondActionTest { @Autowired private MockMvc mvc; // use MockMvcBuilders.webAppContextSetup to create mvc // ... }
请记住,缓存的上下文可以更快地运行多个测试,但如果您在开发时反复运行单个测试,则需要支付创建大量bean的成本,然后立即将其丢弃。