Junit模拟错误:org.mockito.exceptions.misusing.MissingMethodInvocationException

时间:2019-02-28 07:43:24

标签: junit spring-data-jpa mockito

我正在使用spring data JPA创建服务和进行单元测试,我正在使用Junitmockito。在下面的代码中,我试图对服务类进行junit测试。

Room帐户映射服务类依赖于Room Investigator映射服务类,因此我使用Mockito来模拟Room Investigator映射服务类方法,但该方法又调用了同一类的另一个方法。

我尝试如下所示,但是在模仿中出现错误。有人可以告诉我我该怎么做吗?

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)

1 个答案:

答案 0 :(得分:1)

错误消息告诉您...

  
      
  1. 在when()内部,您不是在模拟对象上调用方法,而是在其他对象上调用方法。
  2.   

在这里可能是这样:

Mockito.when(roomInvestMapService.returnRoomWithinClusterByRoomAllocationID(1839))...

...因为:

@Autowired
RoomInvestigatorMappingService roomInvestMapService;

...可能不是模拟的,因为您不使用@MockBean。至少对我来说,这似乎是目前最合理的解释。