java - 用我的函数模拟 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 中我得到一个错误,我不知道解决...
解决方案
@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();
推荐阅读
- performance - 大量删除的文档计数是否会影响 ES 查询性能
- windows - 如何使用 DirectComposition 或 Windows.UI.Composition 平铺位图
- javascript - 用内表填充动态表 - JavaScript
- jquery - 定位固定元素,停止滚动超出页脚,停止时抖动
- python - 伽玛分布的最大似然法
- java - 无法从另一个控制器访问控制器及其方法
- c# - OAuth 2.0 授权:将沙箱更新到 Spring 20 版本后未获得“授权码”
- javascript - 对克隆的表单执行操作
- laravel - Laravel Scout 与 MySQL 全文索引?
- hadoop - 在 Hadoop-3.2.0 中运行 start-dfs.sh 时出错