Reputation: 1439
I am using spring data JPA
for creating services and for unit testing I am using Junit
and mockito
. In following code I am trying to do junit testing for service class.
Room account mapping service class is dependent on Room Investigator mapping service class so I used mockito for mocking room Investigator mapping service class method but that method calling one more method of same class.
I tried like below but I am getting error in mockito. Can any one please tell me how I can do mocking?
TestRoomAccountMappingService class
public class TestRoomAccountMappingService {
@MockBean
RoomAccountMappingRepository roomAccountMapRepository;
@Autowired
RoomAccountMappingService roomAccountMappingService;
@Autowired
RoomInvestigatorMappingService roomInvestMapService;
@Test
public void deleteAccountMapping() {
Integer[] RoomAllocationId= {1839};
//here getting error
Mockito.when(roomInvestMapService.returnRoomWithinClusterByRoomAllocationID(1839)).thenReturn(RoomAllocationId);
RoomAccountMapping roomAcctMap= new RoomAccountMapping();
roomAcctMap.setnRoomAllocationId(1);
List<RoomAccountMapping> roomList= new ArrayList<>();
roomList.add(roomAcctMap);
Mockito.when(roomAccountMapRepository.findByNRoomAllocationId(1839)).thenReturn(roomList);
Boolean actual = roomAccountMappingService.deleteAccountMapping(1839);
assertEquals(true, actual );
}
}
Failure Trace
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
at com.spacestudy.service.TestRoomAccountMappingService.deleteAccountMapping(TestRoomAccountMappingService.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Upvotes: 0
Views: 689
Reputation: 10652
As the error message tells you...
- inside when() you don't call method on mock but on some other object.
This might be the case here:
Mockito.when(roomInvestMapService.returnRoomWithinClusterByRoomAllocationID(1839))...
...because:
@Autowired
RoomInvestigatorMappingService roomInvestMapService;
...is probably not a mock, since you don't use @MockBean
. At least, to me, that seems currently to be the most plausible explanation.
Upvotes: 1