Spring 使用构造函数注入启动 @WebMvcTest 不工作

Spring Boot @WebMvcTest with constructor injection not working

使用 @WebMvcTest 的构造函数注入 NOT 有效。模拟 bean SomeService 未初始化。为什么? Mockito 不会独立于 Spring Boot 创建 SomeService 吗?

如果我使用 @MockBean 一切正常,但我想使用构造函数注入。

有什么想法吗?

@WebMvcTest with constructor injection not working

package com.ust.webmini;

@RequiredArgsConstructor
@RestController
public class HelpController {
    @NonNull
    private final SomeService someService;

    @GetMapping("help")
    public String help() {
        return this.someService.getTip();        
    }
}

-------------------------------------------
package com.ust.webmini;

@Service
public class SomeService {
    public String getTip() {
        return "You'd better learn Spring!";
    }
}
-------------------------------------------

@WebMvcTest(HelpController.class)
public class WebMockTest {

    @Autowired
    private MockMvc mockMvc;
    
/* if we use this instead of the 2 lines below, the test will work!
    @MockBean 
    private SomeService someService;
*/
    private SomeService someService = Mockito.mock(SomeService.class);
    private HelpController adviceController = new HelpController(someService);

    @Test
    public void test() {
         // do stuff        
    }
}
---------------------------------------
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.ust.webmini.HelpController required a bean of type 'com.ust.webmini.SomeService' that could not be found.


Action:

Consider defining a bean of type 'com.ust.webmini.SomeService' in your configuration.

UnsatisfiedDependencyException: Error creating bean with name 'helpController' [...]
NoSuchBeanDefinitionException: No qualifying bean of type 'com.ust.webmini.SomeService' available: expected at least 1 bean

@MockMvcTest 旨在提供一种对特定控制器进行单元测试的简单方法。它不会扫描任何 @Service@Component@Repository beans,但它会选择任何用 @SpyBean@MockBean.

注释的东西

@MockBean 将像 Mockito.mock(...) 一样创建指定类型的模拟,但它还会将模拟实例添加到 spring 应用程序上下文中。 Spring 然后会尝试将 bean 注入到您的控制器中。所以 spring 本质上和你在这里做的一样:

private SomeService someService = Mockito.mock(SomeService.class);
private HelpController adviceController = new HelpController(someService);

我建议坚持使用 @MockBean 方法。此外,如果您需要访问您的 HelpController,只需在您的测试中自动装配它即可。

来自docs:

Using this annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests (i.e. @Controller, @ControllerAdvice, @JsonComponent, Converter/GenericConverter, Filter, WebMvcConfigurer and HandlerMethodArgumentResolver beans but not @Component, @Service or @Repository beans).

If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than this annotation.