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

时间:2016-10-25 09:58:12

标签: java spring spring-boot spring-test

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

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

问题是:

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

1 个答案:

答案 0 :(得分:8)

通过使用两个不同的类@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;

    // ...
}

<强> 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的成本,然后立即将其丢弃。