对Expectations中的模拟对象的JMockit NullPointerException

时间:2013-05-01 20:36:27

标签: java unit-testing mocking jmockit

以下是我的测试用例的相关部分:

@NonStrict
private StowServiceWrapper mockStowServiceWrapper;

@NonStrict
private IsItemStowableResponse mockIsItemStowableResponse;

@NonStrict
private IsItemStowable mockIsItemStowable;

...

@Test
public void testMoveItemActivitySuccess() {
    final MoveItemActivity activity = new MoveItemActivity();        

    final MoveItemRequest request = new MoveItemRequest();

    new Expectations() {

        {
            invoke(activity, "isItemStowable", request); result=mockIsItemStowable;
            //activity.isItemStowable(request); result=mockIsItemStowable;
            mockStowServiceWrapper.isItemStowableToBin(anyString, anyString, anyString, anyString); result=mockIsItemStowableResponse;
            mockIsItemStowableResponse.hasFilterResults();result=false;
        }
    };

    MoveItemResponse response = activity.enact(request);

以下是类源的相关部分(在MoveItemActivity中):

StowServiceWrapper stowServiceWrapper = new StowServiceWrapperImpl();
private IsItemStowable isItemStowable(MoveItemRequest input) {

    IsItemStowable isStowable = new IsItemStowable();
    isStowable.setIsItemStowable(false);

    System.out.println("TEST1");
    /* First check if item is stowable to bin */
    IsItemStowableToBinResponse isItemStowableResponse = stowServiceWrapper.isItemStowableToBin();
    System.out.println("TEST2");
    /* fastFail is 'true' by default, so stow service request will only return one filter violation at a time */
    if (isItemStowableResponse.hasFilterResults()) {
        ...
    }

我在此行收到NullPointerException:if (isItemStowableResponse.hasFilterResults())

我对JMockit比较陌生。我不确定它为什么要在这个方法中执行代码 - 我只想模拟整个方法,因为它是我''enact'方法中的一个依赖项,我正在尝试进行单元测试。

1 个答案:

答案 0 :(得分:0)

    new MockUp<MoveItemActivity>()
    {
        @Mock
        IsItemStowable isItemStowable(MoveItemRequest request) {
            return new IsItemStowable();
        }
    };

好的,想出了如何在被测试的类中模拟一个方法。