Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot WebMvcTest with custom filter difficulties

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.

like image 878
O. Aroesti Avatar asked Dec 20 '25 19:12

O. Aroesti


1 Answers

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.

like image 100
Ken Chan Avatar answered Dec 24 '25 07:12

Ken Chan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!