About 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;
}

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(baseControllerRandoms(isA(ModelAndView.class((.thenReturn(10(;

它也是错误,我不知道如何修复它。

现在是六月4&mockito 5.0

第一次接触JUnit,如何修改测试代码?

我发现您尝试测试的方法在控制器级别baseController中。如果您的方法正在调用更多的方法(假设您在baseService中有更多的逻辑(,则只需要使用Mock

因此,在您的场景中,我只需编写一个测试,设置一个静态预期响应(例如int=10(,并在您调用该方法时断言它与实际响应匹配。

最新更新