我在嘲笑这种方法时做错了什么?

What am I doing wrong in mocking this method?

这是我的测试片段 class。

class MyClassTest {
    MyClass my;
    HandlerA handlerA;
    HandlerB handlerB

    @BeforeTest
    public void setUp() {

        handlerA = mock(HandlerA.class);
        handlerB = mock(HandlerB.class);
        my = new MyClass(handlerA, handlerB);
    }

    @Test
    public void testhandlerABuilderNegativeCase() {

        Shapes s = getShapes();
        Types t = my.buildTypes();
        when(handlerA.handle(s, t)).thenReturn(Response.status(500).type(MediaType.APPLICATION_JSON).build());//ineffective.

        Assert.assertFalse(my.handlerABuilder());
    }

    Shapes getShapes() {
        //returns shapes;
    }
}

这是我的主要 class。

public class MyClass {

    MyClass(HandlerA handleA, HandlerB handleB) {
        this.handleA= handleA;
        this.handleB= handleB;
    }
    ...
    boolean handlerABuilder() {
        Types t = buildTypes();
        Shapes s = getShapes();
        Response resp = handleA.handle(s,t);// resp is always null. despite using when to set 
        return (resp.getStatus==200); // throws NPE
    }
    Types buildTypes(){
        //return types.
    }

    Shapes getShapes() {
        //return shapes.
    }
}

我得到一个 NullPointerException,因为 when 似乎没有正确执行。结果,响应始终返回为 null。关于为什么会发生这种情况的任何想法?我也试过调试,但似乎没有帮助。

你为什么关心传递给 handle 的内容?你正在嘲笑它的结果 无论如何,所以没有理由担心传递任何特定于它的东西。

可能发生的情况是您将 null 传递给它,但处理得不是很好。

您可以做的是更改 when 条件以匹配 any 对象。

when(handlerA.handle(any(Shapes.class), any(Types.class)))
   .thenReturn(Response.status(500).type(MediaType.APPLICATION_JSON).build());