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

2022-09-02 10:42:34

我创建了多个spring-boot测试类(使用spring-boot 1.4.0)。

第一次行动测试.java

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

    // ...
}

第二次行动测试.java

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

    // ...
}

通过以下方式运行测试时:

mvn test

它似乎为每个测试类创建了一个春季测试上下文,我想这不是必需的。

问题是:

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

答案 1

通过将两个不同的类与(即 和 )一起使用,您可以明确指示您需要不同的应用程序上下文。在这种情况下,您无法共享单个上下文,因为每个上下文都包含一组不同的 Bean。如果你是控制器bean,那么上下文应该相对快速地创建,你不应该有问题。@WebMvcTest@WebMvcTest(FirstAction.class)@WebMvcTest(SecondAction.class)

如果你真的想要一个可以在所有Web测试中缓存和共享的上下文,那么你需要确保它包含完全相同的bean定义。我想到了两个选项:

1) 在未指定任何控制器的情况下使用。@WebMvcTest

第一次行动测试:

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

    // ...
}

第二次行动测试:

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

    // ...
}

2)根本不使用,这样你就可以得到一个包含所有bean的应用程序上下文(不仅仅是Web关注点)@WebMvcTest

第一次行动测试:

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

    // ...
}

第二次行动测试:

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

    // ...
}

请记住,缓存的上下文可以使运行多个测试的速度更快,但是如果您在开发时重复运行单个测试,则需要付出创建大量bean的成本,然后立即被丢弃。


答案 2

推荐