gpt4 book ai didi

java - 删除集成测试时创建 bean 的异常,该异常不会出现在标准应用程序启动中

转载 作者:行者123 更新时间:2023-11-30 06:54:45 25 4
gpt4 key购买 nike

我有一个运行良好的 Spring Boot 应用程序,但是当我开始进行集成测试时,我发现项目中存在循环依赖:

@Service
public class CrowdManagerSyncService {
private final CrowdManagerSyncScheduler crowdManagerSyncScheduler;

@Autowired
public CrowdManagerSyncService(CrowdManagerSyncScheduler crowdManagerSyncScheduler) {
this.crowdManagerSyncScheduler = Objects.requireNonNull(crowdManagerSyncScheduler);
}
}

@Component
public class CrowdManagerSyncScheduler {
@Autowired
private CrowdManagerSyncService crowdManagerSyncService;
}

这不是我的代码,我现在还没有准备好重写它。但它在生产中运行得非常好。在我的集成测试中

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
@WithMockUser(roles={"ADMIN"})
@ContextConfiguration(classes = {AdminConsoleApplication.class, DataSourceAutoConfiguration.class,
MockMvcAutoConfiguration.class, MockMvcWebDriverAutoConfiguration.class})
public class UserControllerTest {
@Autowired
private MockMvcHtmlUnitDriverBuilder builder;
private WebDriver webDriver;

@Before
public void setUp() throws Exception {
webDriver = builder.build();
}
}

我捕获异常:

Error creating bean with name 'crowdManagerSyncService': Requested bean is currently in creation: Is there an unresolvable circular reference?

所以,我的问题是:如何在测试中忽略这个问题而不消除那个可怕的循环依赖?它在生产中运行良好,因此非常确定有某种方法可以在不更改代码的情况下启动测试上下文。

最佳答案

@WebMvcTest 不适合“正确的”集成测试。

来自the api docs :

Can be used when a test focuses only on Spring MVC components.

但是,您随后将使用 @ContextConfiguration 将整个应用程序添加到测试中。

删除 @ContextConfiguration 并将 @MockBean CrowdManagerSyncService Autowiring 到您的测试中。这将创建 CrowdManagerSyncService 的模拟版本,并将其注入(inject)到测试应用程序上下文中的 UserController 中。

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
@WithMockUser(roles={"ADMIN"})
public class UserControllerTest {
@Autowired
private MockMvcHtmlUnitDriverBuilder builder;

@MockBean
private CrowdManagerSyncService service;

private WebDriver webDriver;

@Before
public void setUp() throws Exception {
webDriver = builder.build();
}

@Test
public void shouldWork() {
when(service.doStuff())
.thenReturn("Hello"); // regular Mockito mocking
}
}

如果您只是尝试测试 UserController 并回避循环依赖问题,那么这是合适的,因为任何地方都没有“真正的”CrowdManagerSyncService 实例化。

您还可以将 @WebMvcTest@ContextConfiguration 替换为 @SpringBootTest (它像生产一样引导应用程序)和 @AutoConfigureMockMvc(用 MockMvc 替换真正的 HTTP 内容)。

关于java - 删除集成测试时创建 bean 的异常,该异常不会出现在标准应用程序启动中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42068627/

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