Junit mockito to test a public method which internally calls private methods

245 Views Asked by At

I have to write Junit Test cases using Mockito.
The method which I have to test is public method but internally it calles few private methods to get some DB data (Using EntityManager and Nativequery without any Repository or Dao class) or perform some other operations.
Method looks like:

public List<UserResponseDto> getUserDetails(UserRequestDto request){
  UserDto= getUserByNativeQuery(rquest);
  List<Object[]> listObj=getUserDetailsByNativeQuery(request);
 List<UserResponseDto> response=setUserResponseDto(listObj);

return response
}

private UserDto getUserByNativeQuery(UserRequestDto request){
//by using EntityManager and NativeQuery to fetch data
}  

private List<Object[]> getUserDetailsByNativeQuery(UserRequestDto request){
//by using EntityManager and NativeQuery to fetch data
}

I am not getting to handle these private method calls so that wthen these methods call I can return test data.

I Don't want to use any other tools or library

1

There are 1 best solutions below

0
LenglBoy On

The anser poorly is that you private methods are nice in order to make code modular and maintainable BUT you need to take into account that private methods need to be tested as implicit.

Implicit testing means that you need to handle your method like all private-method logic is writting at the public method. At some point this makes re-used privat method gets tested redundently.

Since you're using mocks this should not be a big deal. Just write yuor test checking public + the used privat methods.

Personally I know that there are tools or ways to mock even private methods BUT you need to provide mock-statements, test-data, ... so it is more clear and easy to just to it implicitly without using any other tool that avoids the common approach and scopes.