spring-boot testing - 多个测试可以共享一个上下文吗?

Eri*_*ang 14 java spring spring-test spring-boot

我创建了多个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;

    // ...
}
Run Code Online (Sandbox Code Playgroud)

SecondActionTest.java:

@RunWith(SpringRunner.class)
@WebMvcTest(SecondAction.class)
@TestPropertySource("classpath:test-application.properties")
public class SecondActionTest {
    @Autowired
    private MockMvc mvc;

    // ...
}
Run Code Online (Sandbox Code Playgroud)

运行测试时:

mvn测试

它似乎为每个测试类创建了一个弹簧测试上下文,我猜这是不必要的.

问题是:

  • 是否可以在多个测试类之间共享一个弹簧测试上下文,如果是,如何?

Phi*_*ebb 9

通过使用两个不同的类@WebMvcTest(即@WebMvcTest(FirstAction.class)@WebMvcTest(SecondAction.class)),您特别指出您需要不同的应用程序上下文.在这种情况下,您不能共享单个上下文,因为每个上下文包含一组不同的bean.如果你的控制器bean表现得相当好,那么上下文应该相对快速地创建,你不应该真的有问题.

如果您确实希望在所有Web测试中都有一个可以缓存和共享的上下文,那么您需要确保它包含完全相同的bean定义.我想到两个选择:

1)使用时@WebMvcTest不指定任何控制器.

FirstActionTest:

@RunWith(SpringRunner.class)
@WebMvcTest
@TestPropertySource("classpath:test-application.properties")
public class FirstActionTest {
    @Autowired
    private MockMvc mvc;

    // ...
}
Run Code Online (Sandbox Code Playgroud)

SecondActionTest:

@RunWith(SpringRunner.class)
@WebMvcTest
@TestPropertySource("classpath:test-application.properties")
public class SecondActionTest {
    @Autowired
    private MockMvc mvc;

    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

SecondActionTest:

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource("classpath:test-application.properties")
public class SecondActionTest {
    @Autowired
    private MockMvc mvc; // use MockMvcBuilders.webAppContextSetup to create mvc

    // ...
}
Run Code Online (Sandbox Code Playgroud)

请记住,缓存的上下文可以更快地运行多个测试,但如果您在开发时反复运行单个测试,则需要支付创建大量bean的成本,然后立即将其丢弃.

  • 对于自动装配 MockMvc,您还可以在执行“@SpringBootTest”时添加注释“@AutoConfigureMockMvc” (2认同)