【发布时间】:2021-11-16 10:39:05
【问题描述】:
源代码:
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;
}
Junit 代码:
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,如何修改测试代码?
【问题讨论】:
-
既要测试控制器又要模拟它,那么测试有什么用呢?