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?!
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;
}
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