I'm using JWT authentication via custom filter that uses several @Services.
like so
@Component
public class JwtAuthentiationFilter extends OncePerRequestFilter {
private final UserService;
...
}
(I'm autowiring the services in the constructor)
Now, I have a controller that I want to test:
@RestController
@RequestMapping(...)
public class COmputerDeviceController {
@GetMapping
@PreAuthorize("hasAuthority('devices)")
public List<Device> getDevices() {
...
}
}
I wanted to test the controller & security, like so:
@RunWith(SpringRunner.class)
@WebMvcTest(ComputerDeviceController.class)
public class ComputerDeviceControllerTest {
@Autowired
private MockMvc mvc;
@WithMockUser
@Test
public void test() throws Exception {
...
}
}
The problem arises from the use of the filter - when trying to run the test, I get NoSuchBeanDefinitionException(No qualifying bean of type UserService available)
I know I can run it as an integration test, but really it just tests the controller and there isn't a need for that, aside for the custom filter & Spring Security.
How can I solve this? I've tried different solutions, like adding @ComponentScan.Filter, and included dependencies manually, but in the end I have to provide entitymanager, which doesn't seems right.
From the docs , @WebMvcTes will register JwtAuthentiationFilter as the spring bean but not its dependencies , you have to use @MockBean to declare these dependencies.
@RunWith(SpringRunner.class)
@WebMvcTest(ComputerDeviceController.class)
public class ComputerDeviceControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private UserService userService;
@WithMockUser
@Test
public void test() throws Exception {
//Then you can stub userService behaviour here..
}
}
The same applied to all dependencies of all bean that are auto registered as spring beans by @WebMvcTest which includes @Controller, @ControllerAdvice, @JsonComponent, Converter, GenericConverter, Filter, WebMvcConfigurer, and HandlerMethodArgumentResolver.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With