带有构造函数注入的Spring Boot@WebMvcTest不起作用



@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@Repositorybean,但会拾取任何用@SpyBean@MockBean注释的bean。

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

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

我建议坚持@MockBean方法。此外,如果您需要访问HelpController,只需在测试中自动连接即可。

来自文档:

使用此注释将禁用完全自动配置,而只应用与MVC测试相关的配置(即@Controller、@ControllerAdvice、@JsonComponent、Converter/GenericConverter、Filter、WebMvcConfigurer和HandlerMethodArgumentResolver beans,而不是@Component、@Service或@Repository beans(。

如果你想加载完整的应用程序配置并使用MockMVC,你应该考虑将@SpringBootTest与@AutoConfigureMockMvc结合起来,而不是这个注释。

最新更新