Constructor injection with @WebMvcTest is NOT working. The mocked bean SomeService is not initialized. Why? Doesn't Mockito create SomeService independently of Spring Boot?
If I use @MockBean everything is ok but I'd like to make use of constructor injection.
Any ideas?
@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