首页 > 解决方案 > 关于 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,如何修改测试代码?

标签: javajunitmockito

解决方案


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

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


推荐阅读