gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:55:14 26 4
gpt4 key购买 nike

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

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

问题是:

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

最佳答案

通过 @WebMvcTest 使用两个不同的类(即 @WebMvcTest(FirstAction.class)@WebMvcTest(SecondAction.class))您明确表示您需要不同的应用程序上下文。在这种情况下,您不能共享单个上下文,因为每个上下文都包含一组不同的 bean。如果你的 Controller bean 表现得相当好,那么创建上下文应该相对较快,你应该不会有问题。

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

1) 使用 @WebMvcTest 而不指定任何 Controller 。

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 的成本,然后这些 bean 会立即被丢弃。

关于java - spring-boot testing - 多个测试可以共享一个上下文吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40236904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com