【发布时间】:2020-08-11 02:43:41
【问题描述】:
@WebMvcTest 的构造函数注入不工作。模拟的 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
【问题讨论】:
标签: spring-boot unit-testing spring-mvc constructor-injection spring-mvc-test