I've a @RestController which has only one dependency in field @Autowire
that dependency is @component, that component Class definition has some autowired fields which are @service and those services have some @repositories.
In this whole flow I've kafka, Quartz, Cassandra and DB2 So when I was creating a Unit test case for my controller, I dont want to setup whole application. so I decided to use @webMvcTest and used @MockBean on my only one dependency of controller class.
But my Test is throwing and exception because its trying to create a Dao bean, which is marked as @repository.
@ActiveProfiles("test")
@WebMvcTest(controllers = MyControllerTest .class)
class MyControllerTest {
@MockBean
MyControllerDependency dependency;
@Autowired
MockMvc mockMvc;
@Test
void test_something() throws Exception {
assert(true);
}
}
Here is oversimplified version of code
@Component
class MyControllerDependency {
@AutoiWired
MyCustomService service;
}
@Service
class MyCustomService{
@Autowired
MyCustomDao dao;
}
@Repository
class MyCustomDao{
@Autowired
private JdbcTemplate template;
}
I'm getting following exception in test.
Exception
***************************
APPLICATION FAILED TO START
***************************
Description:
Field template in com.....MyCustomDao` required a bean of type 'org.springframework.jdbc.core.JdbcTemplate' that could not be found.
Question is, When I'm using @WebMvcTest slice and already mocking the only required dependency MyControllerDependency then why spring test context is trying to load MyCustomDao which is annotated as @Repository.
I can do integration testing with SpringbootTest & AutoconfigureMockMVC, but for writing Junit test just for controller, I need to use WebMvcTest slice. which is creating a problem.
I ran into a similar problem where I want to test only my controller using @WebMvcTest, but the spring context was trying to create nondependent spring beans and was failing as below.
Failed to load ApplicationContext java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'TestController' defined in file ...
Solution: load only the controller your testing for an example like @ContextConfiguration(classes = DemoController.class).
Also, find below a complete sample
@WebMvcTest
@ContextConfiguration(classes = DemoController.class)
public class DemoControllerTest {
@Autowired
MockMvc mockMvc;
@MockBean
DemoService demoService;
@Test
public void testGetAllProductCodes_withOutData() throws Exception {
when(productCodeService.getAllProductCodes())
.thenReturn(new ArrayList<ProductCodes>());
mockMvc.perform(MockMvcRequestBuilders.get("/services/productCodes"))
.andExpect(MockMvcResultMatchers.status().isNoContent());
}
}
}
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