使用自定义参数匹配器时,第二次调用Mockito.NPE将

时间:2019-03-27 14:19:07

标签: java unit-testing mockito junit4

美好的一天。

假设我有一个界面。该接口具有接受某些类的一个或两个实例的方法。在单元测试类中,我模拟了此接口,并希望使用以下逻辑对其进行模拟:

  1. 如果参数与template1匹配,则返回value1
  2. 如果参数与template2匹配,则返回value2

当我仅模拟第一种情况时,测试运行顺利。当我添加第二种情况(以及第一种情况)时,NPE会导致测试崩溃:

java.lang.NullPointerException
at org.some.pkg.TestTest$ArgMatcher.matches(TestTest.java:54)
at org.some.pkg.TestTest$ArgMatcher.matches(TestTest.java:43)
at org.mockito.internal.invocation.TypeSafeMatching.apply(TypeSafeMatching.java:24)
at org.mockito.internal.invocation.MatcherApplicationStrategy.forEachMatcherAndArgument(MatcherApplicationStrategy.java:83)
at org.mockito.internal.invocation.InvocationMatcher.argumentsMatch(InvocationMatcher.java:152)
at org.mockito.internal.invocation.InvocationMatcher.matches(InvocationMatcher.java:81)
at org.mockito.internal.stubbing.InvocationContainerImpl.findAnswerFor(InvocationContainerImpl.java:91)
at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:87)
at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)
at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:35)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:63)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:49)
at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptAbstract(MockMethodInterceptor.java:128)
at org.some.pkg.Interface$MockitoMock$1549778145.callMe(Unknown Source)
at org.some.pkg.TestTest.test(TestTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

[MockitoHint] TestTest.test (see javadoc for MockitoHint):
[MockitoHint] 1. Unused... -> at org.some.pkg.TestTest.test(TestTest.java:24)
[MockitoHint]  ...args ok? -> at org.some.pkg.TestTest.test(TestTest.java:29)


Process finished with exit code 255

下面是设置示例。

文件:Interface.java-模拟接口

package org.some.pkg;

public interface Interface {
    public class Arg {
        private String str;
        private int v;

        public Arg(String str, int v) {
            this.str = str;
            this.v = v;
        }

        public String getStr() {
            return str;
        }

        public int getV() {
            return v;
        }
    }

    int callMe(Arg a1, Arg a2);
}

文件:TestedClass.java-一些委托类(实际测试过的类)

package org.some.pkg;

import org.springframework.beans.factory.annotation.Autowired;

public class TestedClass {
    @Autowired
    Interface delegate;

    int callMe(Interface.Arg a1, Interface.Arg a2) {
        int x = delegate.callMe(a1, a2);

        return x * 2;
    }
}

文件:TestTest.java-测试

package org.some.pkg;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class TestTest {
    @Mock
    private Interface iface;

    @InjectMocks
    private TestedClass testedClass;

    @Test
    public void test() {
        // when-1
        when(iface.callMe(
                argThat(new ArgMatcher("start1", 10)),
                argThat(new ArgMatcher("start2", 5))
        )).thenReturn(10);

        // when-2
        when(iface.callMe(
                argThat(new ArgMatcher("start3", 5)),
                argThat(new ArgMatcher("start4", 2))
        )).thenReturn(3);

        // test
        int v = testedClass.callMe(
                new Interface.Arg("start1 suffix", 3),
                new Interface.Arg("start2, suffix", 4));

        System.out.println("V = " + v);

        Assert.assertEquals(20, v);
    }

    class ArgMatcher implements ArgumentMatcher<Interface.Arg> {
        private final String start;
        private final int threshold;

        public ArgMatcher(String start, int threshold) {
            this.start = start;
            this.threshold = threshold;
        }

        @Override
        public boolean matches(Interface.Arg argument) {
            return argument.getV() < threshold && argument.getStr().startsWith(start);
        }
    }
}

如果我注释掉when-2块,则测试运行顺利且顺利。否则,我会看到没有明显原因的NPE。

Mockito的版本为2.24.0 JUnit是版本4。

更新:第二次调用Mockito.when的过程是一些知识,即在一个单元测试中可以多次调用模拟方法。

2 个答案:

答案 0 :(得分:0)

好吧,我发现了使用when(mock.callMe(any(Arg.class), any(Arg.class))).thenAnswer(new Answer<Integer> { ...});

的解决方法

答案 1 :(得分:0)

使用Mockito 2.28.2和3.1.0:

面对类似的问题和解决方案是按照@Morfic提出的方式进行,即重写(假设Mockito是静态导入的):

when(someMock.someMethod(argThat(...))).thenReturn(someValue);

具有:

doReturn(someValue).when(someMock).someMethod(argThat(...));

但是我不知道为什么第一个失败而第二个工作正常...

JUnit 4测试用例以显示失败和工作选项:

class MyBean{
    public Integer id;
    public String name;

    public MyBean(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

interface MyService{
    Integer measure(MyBean myBean);
}

    @Test
    public void testThatFailsWithNPE(){

        when(myService.measure(argThat((mb) -> Objects.equals(mb.id, 123) && Objects.equals(mb.name, "123")))).thenReturn(123);
        when(myService.measure(argThat((mb) -> Objects.equals(mb.id, 321) && Objects.equals(mb.name, "321")))).thenReturn(321);

        assertEquals(Integer.valueOf(123), myService.measure(new MyBean(123, "123")));
        assertEquals(Integer.valueOf(321), myService.measure(new MyBean(321, "321")));
        assertEquals(Integer.valueOf(0), myService.measure(new MyBean(777, "777")));
    }

    @Test
    public void testThatPasses(){

        doReturn(123).when(myService).measure(argThat((mb) -> Objects.equals(mb.id, 123) && Objects.equals(mb.name, "123")));
        doReturn(321).when(myService).measure(argThat((mb) -> Objects.equals(mb.id, 321) && Objects.equals(mb.name, "321")));

        assertEquals(Integer.valueOf(123), myService.measure(new MyBean(123, "123")));
        assertEquals(Integer.valueOf(321), myService.measure(new MyBean(321, "321")));
        assertEquals(Integer.valueOf(0), myService.measure(new MyBean(777, "777")));
    }