java - 关于 Junit Mockito
问题描述
源代码:
public int Randoms(ModelAndView model) {
int ra =0;
if(model!=null){
Random random = new Random();
ra=random.nextInt(10) + 1;
model.addObject("ra", ra);
}
return ra;
}
简码:
public void testRandoms() throws Exception {
when(baseController.Randoms(any())).thenReturn(10);
ModelAndView modelAndView = mock(ModelAndView.class);
modelAndView.setViewName("test");
int result = baseController.Randoms(modelAndView);
Assert.assertTrue(result<10);
}
错误信息:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at com.hp.billing.controller.BaseControllerTest.testRandoms(BaseControllerTest.java:29)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(any());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
错误代码:when(baseController.Randoms(any())).thenReturn(10);
但我尝试编辑:when(baseController.Randoms(isA(ModelAndView.class))).thenReturn(10);
这也是错误,我不知道如何解决它。
这是 Junit4 和 mockito 5.0
第一次接触JUnit,如何修改测试代码?
解决方案
我看到您尝试测试的方法是在控制器级别baseController
。如果您的方法正在调用更多方法,则只需要使用 Mock (假设您在 中有更多逻辑baseService
)
因此,在您的场景中,我只需编写一个测试,设置一个静态预期响应(例如 int = 10),并在您调用该方法时断言它与实际响应相匹配。
推荐阅读
- python - 如何从 Python 字典中删除区分大小写
- python - pandas 如何处理方括号 [] 以及如何避免这种情况?
- javascript - return 语句将在 nodejs 中的 router.post 中执行什么操作
- python - 遍历多个列表并根据每次迭代分配变量
- spring-boot - 无法加载资源 api vue.js
- vbscript - 从 VB 脚本中查找并重新加载 Edge 浏览器窗口?
- javascript - 通过 get() 方法获取属性与将其分配给 web 组件上 connectedCallback 内的变量?
- css - HTML-CSS 如何将元素绑定到另一个元素的右侧?例如输入按钮(左) - 输入文本或任何其他(右)
- java - 在哪里可以获取 Google Ads API URL 端点以调用 Postman?
- javascript - 如何在 AJAX 调用中遍历纬度/经度对数组