首页 > 解决方案 > 用我的函数模拟 MissingMethodInvocationException

问题描述

我正在使用 Springboot 和 Mockito 进行测试。

我想模拟一个她返回字符串的函数。

代码实现:

编辑

public String replaceContent(String url, String replace, String value) {
    return url.replace(replace, value);
}


public ResponseEntity<List<MonitorOperativeFront>> getOperativesMonitor(String userCode) {

log.info(" ---> LogInfo: start ");

String url = this.replaceContent(this.urlBase,this.stringReplace,userCode);

log.info(" ---> LogInfo: call to: " + url);
List<MonitorOperativeFront> list= null ;

MonitorOperative[] operative = this.restTemplate.getForObject(url, MonitorOperative[].class);
list.add(new MonitorOperativeFront(operative[0].getId()));
log.info(" ---> LogInfo: Success ");


return new ResponseEntity<>(list, HttpStatus.OK);

}


代码测试:

@Mock
Mockito mk;
@InjectMocks
MonitorServiceImpl monitorService;

    @Test
    public void testG() throws Exception {
        String url = "prueba/test";
        this.mk.when( monitorService.replaceContent("prueba/{id}", "{id}", "test"))
                .thenReturn(url);
    ResponseEntity<List<MonitorOperativeFront>> operative2 = monitorService.getOperativesMonitor("n11111");
    assertEquals(true,true);

呃:

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.

我检查了我的函数是否返回成功“prueba/test”,但在 mockito 中我得到一个错误,我不知道解决...

标签: javamockito

解决方案


@Mock 应该是具有您想要模拟的方法的类。如果你想模拟你必须写的 replaceContent

@Mock
MonitorServiceImpl monitorServiceMock;

@InjectMocks
SomeUserOfMonitorServiceImpl monitorServiceImplUser;

@Test
public void testG() throws Exception {
   String url="http://dsgdfgdf/"
   Mockito.when( monitorServiceMock.replaceContent("prueba/{id}", "{id}", "test"))
            .thenReturn(url));
   //Do Something which calls the monitorService.replaceContent 
   monitorServiceImplUser.doSomething();

推荐阅读