I'm trying to mock this method:
public ClassService{
ClassResponseDTO method1(String var1, GenericDTO<ClassDTO> var2){
//Code
}
}
My mock:
ClassResponseDTO respRev = new ClassResponseDTO ();
ClassService classService = new ClassService();
when(classService.method1(any(String.class)
, ArgumentMatchers.<GenericDTO<ClassDTO>>any()))
.thenReturn(respRev);
I'm getting a unnecesary stubbing error. Please Help.
Related
I am trying to mock queryForObject method using Mockito. Unit test actually is passed but the lines is not fully covered.
The code to get the people object is like below:
jdbcTemplate.queryForObject(GET_PEOPLE,
(rs, rowNum) -> new People()
.setId(rs.getInt("id"))
.setFirstName(rs.getString("first_name"))
.setLastName(rs.getString("last_name")),
department, position);
FYI: GET_PEOPLE is a static constant contain the SQL query.
and the unit test is:
People people = new People();
people.setId(1);
people.setFirstName("John");
people.setLastName("Doe");
when(jdbcTemplate.queryForObject(any(), (RowMapper<Object>) any(), any())).thenReturn(people);
Can anyone let me know how to mock to get the lines fully covered. Thanks in advance.
You are not getting coverage because you never execute that code.
You need to call your rowmapper:
#ExtendWith(MockitoExtension.class)
public class MyTest {
#Mock
JdbcTemplate jdbcTemplate;
#Mock
ResultSet resultSet;
#Test
public void myTest() throws SQLException {
when(resultSet.getInt(1)).thenReturn(1);
...
when(jdbcTemplate.queryForObject(any(), (RowMapper<People>) any(), any())).thenAnswer(new Answer<People>() {
#Override
public People answer(InvocationOnMock invocationOnMock) throws Throwable {
RowMapper<People> rowMapper = invocationOnMock.getArgument(1);
return rowMapper.mapRow(resultSet, 1);
}
});
...
}
}
I've been learning Java for about 4 months, so please excuse basic mistakes.
I'm trying to unit test a method from my Service layer:
#Override
#Transactional
public List<StudentDto> getStudentList() {
List<Student> tempList = studentDAO.getStudentList();
List<StudentDto> tempListStudentDto = new ArrayList<>();
for (Student theStudent: tempList) {
tempListStudentDto.add(convertToDto(theStudent));
}
return tempListStudentDto;
}
With this #Test:
// JUnit test for getStudentList()
#Test
#DisplayName("getStudentList()")
public void givenStudentList_whenGettingList_thenReturnList() {
// given -precondition
BDDMockito.given(studentDao.getStudentList())
.willReturn(List.of(newStudentOne, newStudentTwo));
// when - behaviour that we are going to test
List<StudentDto> studentList = studentService.getStudentList();
// then - verify the output
assertAll(
() -> org.assertj.core.api.Assertions.assertThat(studentList).isNotNull(),
() -> org.assertj.core.api.Assertions.assertThat(studentList).size().isEqualTo(2)
);
And I'm constantly getting this error:
java.lang.NullPointerException: Cannot invoke "org.modelmapper.ModelMapper.getConfiguration()" because "this.modelMapper" is null
Could you please help me here or tell me how to convert the Student class to DTO in a testable way?
I've googled the issue and tried all of the suggestions, but could not make it to work.
I have the following controller method where criterias is an object build with query parameters :
#GetMapping
public List<Employee> findAll(CustomCriteria criterias) {
// this method build a custom mongoDB query object
final Query query = criterias.buildMongoDBQueryFromCriteria();
return employeeService.find(query);
}
The test is written as follow :
#Test
void get_all_employees_with_criterias() {
given(employeeService.find(any(Query.class)))
.willReturn(List.of(new Employee(), new Employee));
final var responseBody = mvc.perform(get("/employees?companyId=12,14")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn()
.getResponse().getContentAsString();
assertThatJson(responseBody).isArray().size().isEqualTo(2);
}
I can't find how to mock criterias.buildMongoDBQueryFromCriteria(). Indeed, there are a lot of logic inside this method, and I don't want it to be called for real with #WebMvcTest.
I have already tried to use #Spy annotation in the controller test class but it doesn't seems to work :/
I'm pretty sure that it must be really basic, but I didn't find any equivalent needs over Google.
Thanks for your help
EDIT
Based on #nnhthuan response I updated my test as follow, but it still doesn't work:
#Test
void get_all_employees_with_criterias() {
var customCriteriaMock = Mockito.mock(CustomCriteria.class);
var mockedQuery = Mockito.mock(Query.class);
when(customCriteriaMock.buildMongoDBQueryFromCriteria()).thenReturn(mockedQuery);
given(employeeService.find(mockedQuery))
.willReturn(List.of(new Employee(), new Employee()));
final var responseBody = mvc.perform(get("/employees?companyId=12,14")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn()
.getResponse().getContentAsString();
assertThatJson(responseBody).isArray().size().isEqualTo(2);
}
If you're asking how to write unit test, and this is how, not what you're trying to write above.
#Test
public void testFindAll() {
CustomCriteria mockCriteria = Mockito.mock(CustomCriteria.class);
Query mockQuery = Mockito.mock(Query.class);
List<Employee> expectation = new ArrayList<>();
when(mockCriteria.buildMongoDBQueryFromCriteria()).thenReturn(mockQuery);
when(employeeService.find(mockQuery)).thenReturn(expectaion)
List<Employee> actual = controller.findAll(mockCriteria);
assertThat(actual).sameInstance(expectation); // Or whatever framework you are using to assert.
}
If you're asking how to write integration test with your real service, so do not use mocking framework. :)
I have a method that calls another mehide inside.
Here is my method:
public void unblocUser(BloclistDTO bloclistDTO) {
blocListRepository.delete(mapper.toModel(bloclistDTO));
if (blocListRepository.getBlocList(bloclistDTO.getCandidate().getId(), bloclistDTO.getColumnName()).isEmpty()) {
this.setVisibility(bloclistDTO.getCandidate().getId(), bloclistDTO.getColumnName(), true);
}
}
I've tested the method setVisibility itself, it works. But, when clling unblocUser it doesn't work ;
Here is how am testing it:
#Test
public void unblocUserLastOne() {
Company blockedCompany = new Company ();
Candidate candidate = new Candidate ();
candidate.setId(1L);
candidate.setPersonalDetailsVisible(false);;
blockedCompany.setId(2L);
candidate.setPersonalDetailsVisible(false);
BloclistDTO bloclist= new BloclistDTO();
bloclist.setBlockedCandidate(null);
bloclist.setCandidate(candidate);
bloclist.setBlockedCompany(blockedCompany);
bloclist.setColumnName("personal_details_visible");
bloclist.setId(3L);
blocListService.unblocUser(bloclist);
assertEquals(true, candidate.isPersonalDetailsVisible());
}
I get an error : expected true but was false.
Any help please ?
first you need to create a mock object for BlocListRepository class
#InjectMocks
BlocListRepository blocListRepository;
Then mock the delete method in BlocListRepository class.
#Test
public void unblocUserLastOne() {
Mockito.doNothing().when(blocListRepository).delete(Mockito.any());
Company blockedCompany = new Company ();
Candidate candidate = new Candidate ();
candidate.setId(1L);
candidate.setPersonalDetailsVisible(false);;
blockedCompany.setId(2L);
candidate.setPersonalDetailsVisible(false);
BloclistDTO bloclist= new BloclistDTO();
bloclist.setBlockedCandidate(null);
bloclist.setCandidate(candidate);
bloclist.setBlockedCompany(blockedCompany);
bloclist.setColumnName("personal_details_visible");
bloclist.setId(3L);
blocListService.unblocUser(bloclist);
assertEquals(true, candidate.isPersonalDetailsVisible());
}
I've been looking on internet but haven't found the solution if any (new on UnitTest and Mockito)
It's possible to test a method that return a call of a service and manipulate it's result before to return it? Example;
public Observable<Reports> getUserReports(Integer userId) {
return serviceClient
.getReports(userId)
.flatMap(serviceReports -> {
System.out.println("Testing inside flatMap"); <- never reach this line therefore duno if methods down here are invoked and work perfectly
final Observable<List<Report>> reports = getPendingReports(userId, serviceReports);
//More methods that modify/update information
return zip(observable1, observable2, observable3
(report1, report2, report3) -> {
updateReports(otherArguments, report1, report2, report3);
return serviceReports;
});
});
}
So far I've tried;
#Test
public void myTest(){
when(serviceClient
.getReports(anyInt()))
.thenReturn(Observable.just(reports));
Observable<Reports> result = mocketClass.getUserReports(userId)
}
Tryed with Spy and Mock but no luck so far. Any hint or help would be great.
To mock getReports() behavior you need to mock the serviceClient firstly and pass it into your service class.
Just as example:
#Test
public void myTest(){
// Given
final ServiceClient mockedServiceClient = Mockito.mock(ServiceClient.class);
when(mockedServiceClient
.getReports(anyInt()))
.thenReturn(Observable.just(reports));
// and create an instance of your class under testing with injected mocked service client.
final MyUserService userService = new MyUserService();
userService.setServiceClient(mockedServiceClient);
// When run a method under test
Observable<Reports> actualResult = userService.getUserReports(userId)
// Then
// actualResult to be verified.
}