I am writing unit test for a controller of my spring boot application. I have typical MVC classes: ObjectSchemaController, ObjectSchemaService and ObjectSchemaDao. I have written unit test with @WebMvcTest and mocked my service and dao class with @MockBean. (following this guide: https://www.baeldung.com/spring-boot-testing)
Below is my unit test :
@RunWith(SpringRunner.class)
@WebMvcTest(ObjectSchemaController.class)
public class ObjectSchemaControllerTest2 {
@Autowired
private MockMvc mvc;
@MockBean
private ObjectSchemaService service;
@MockBean
private ObjectSchemaDao dao;
@Autowired
ObjectMapper objectMapper;
@Test
public void testCreateObjectSchemaPass() throws Exception {
String payload = "{\"some_key\":\"some val\"}";
ObjectSchema objectSchema = objectMapper.readValue(payload, ObjectSchema.class);
Mockito.when(service.createSchema(objectSchema))
.thenReturn(objectSchema);
Mockito.when(dao.createSchema(objectSchema)).thenReturn(objectSchema);
mvc.perform(MockMvcRequestBuilders.post("/objectservice/schema/")
.contentType("application/json")
.content(objectMapper.writeValueAsString(objectSchema)))
.andExpect(status().isOk());
}
}
below is my service class:
@Service
public class ObjectSchemaService {
@Autowired
ObjectSchemaDao objectSchemaDao;
public ObjectSchema createSchema(@Valid ObjectSchema objectSchema)throws Exception {
return objectSchemaDao.createSchema(objectSchema);
}
}
The issue I am facing with Unit test is, the service layer doesn't get executed and returns null value.
When I debug, I can see execution reaching in my controller class and ObjectSchemaService as being mockito-mocked in the controller. But the execution never goes in service layer and the value returned by service method is null.
I have referenced other guides- they are doing similar steps. But its not working for me. What am I missing here?
I have also seen this post with similar issue.
Unit Test POST with @WebMvcTest - @MockBean Service returns null
I made sure the input objects to both my actual controller and the one I am passing in unit case are instances of same class.
You are mocking the ObjectSchemaService
but no behaviour is expected.
You need to setup the behaviour for the services that are mocked. So depending on the method signature and result somethink like.
Mockito.when(service.createSchema(Mockito.any(ObjectSchema.class)).thenReturn(objectSchema);
At the moment the ObjectSchemaService mock just returns a default value which is null in your case.
In order to be transparent and unobtrusive all Mockito mocks by default return 'nice' values. For example: zeros, falseys, empty collections or nulls.
If you update your answer with details for ObjectSchemaService
I could also update my answer.