我正在使用spring data JPA
来创建服务,并且用于单元测试,我正在使用Junit
和mockito
。在以下代码中,我试图为服务类进行JUNIT测试。
房间帐户映射服务类取决于房间调查员映射服务类,因此我使用Mockito进行模拟房间调查员映射服务类方法,但是该方法调用了同一类的另一种方法。
我尝试过下面的尝试,但在Mockito中遇到了错误。有人可以告诉我如何嘲笑吗?
TestRoomAccountMappingservice类
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 );
}
}
失败跟踪
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)
正如错误消息告诉您...
- 内部()()您不在模拟上调用方法,而在其他某些对象上调用方法。
这里可能是这种情况:
Mockito.when(roomInvestMapService.returnRoomWithinClusterByRoomAllocationID(1839))...
...因为:
@Autowired
RoomInvestigatorMappingService roomInvestMapService;
...可能不是模拟,因为您不使用@MockBean
。至少对我而言,目前似乎是最合理的解释。