Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add one additional bean to "@WebMvcTest"

I have a controller and a test using @WebMvcTest and its running fine. Now i needed to add a little validation logic and for this i @Autowired an additional bean (a @Component, a MapstructMapper).

As expected now the test is failing due to @WebMvcTest. (No components are discovered)

Is there a way to add one bean to the context created?

Since i am using @MockBeans to mock service layer: is there a way to delegate all mock calls to a real object? With this i could mock the mapper and delegate to real mapper?!

like image 364
dermoritz Avatar asked May 07 '19 11:05

dermoritz


1 Answers

A very simple solution is to annotate your test class with @Import specifying the class(es) of the additional bean(s) you want to use in your test, as stated in documentation:

Typically @WebMvcTest is used in combination with @MockBean or @Import to create any collaborators required by your @Controller beans.

e.g.

@WebMvcTest(MyController.class)
@Import(SomeOtherBean.class)
public class SourcingOrganisationControllerTests {

    // The controller bean is made available via @WebMvcTest  
    @Autowired
    private MyController myController;

    // Additional beans (only one in this case) are made available via @Import
    @Autowired
    private SomeOtherBean someOtherBean;
}
like image 89
Dónal Avatar answered Jan 02 '23 03:01

Dónal