You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot集成测试报错:找不到IndexService自动装配候选Bean

控制器到服务层全链路集成测试问题及解决方案

问题场景

我想编写不Mock任何类的集成测试,完整覆盖从控制器到服务层的流程,但测试时无法进入服务层,抛出如下错误:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'service.index.service.IndexService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

如果用@MockBean模拟IndexService,接口会返回200状态码,但这样没法测试服务层的实际逻辑——正常执行服务层逻辑应该返回201状态码。请问怎么实现从控制器到服务层的全链路测试?

原测试代码

@WebMvcTest(controllers = Controller.class)
class ControllerTest {

@Autowired
private WebApplicationContext webApplicationContext;

@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper mapper;

@Autowired
private IndexService indexService;

private String baseUrl = "https://localhost/";

@Test
void createIndex() throws Exception {

    CreationInputDto input = new CreationInputDto();

    MvcResult result = mockMvc.perform(
            post(baseUrl+"/create")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(mapper.writeValueAsString(input))
            )
            .andExpect(status().is(201))
            .andReturn();


    String content = result.getResponse().getContentAsString();
}}

补充说明:我的IndexService包含多个自动注入的参数,其中部分是难以实例化的接口。

解决方案

改用@SpringBootTest结合WebTestClient实现全链路测试,成功覆盖控制器到服务层的实际逻辑,最终代码如下:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ControllerTest {

@Autowired
private WebTestClient webTestClient;

@Test
void createIndex() {
    
    CreationInputDto input = new CreationInputDto();

    WebTestClient.ResponseSpec result = webTestClient
            .post()
            .uri("/create")
            .body(Mono.just(input), CreationInputDto.class)
            .exchange()
            .expectStatus().isEqualTo(201);
}}

内容的提问来源于stack exchange,提问作者Bahar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 02:19:57