测试方法传递的空指针异常

时间:2019-06-17 08:25:38

标签: java android unit-testing mockito android-testing

  

需要测试的方法-位于AnalyticsServiceImpl.java类

public void trackSplashState(MeasurementViewEnum measurementViewEnum) {
    HashMap<String, Object> data = createCommonData(measurementViewEnum);
    MeasureServiceImpl.StartStatus status = mMeasureService.getLaunchStatus();
    switch (status) {
        case INSTALL:
            data.put(APP_EVENT_INSTALL, INSTALL);
            break;
        case LAUNCH:
            data.put(APP_EVENT_LAUNCH, LAUNCH);
            break;
        case UPDATE:
            data.put(APP_EVENT_UPDATE, UPDATE);
            break;
    }
    trackState(measurementViewEnum, data);
}
     

测试类

@Config(constants = BuildConfig.class, sdk = TestConfig.SDK)
@RunWith(RobolectricTestRunner.class)
public class AnalyticsServiceImplTest {

    @Module(includes = TestAppModule.class, injects = AnalyticsServiceImplTest.class, overrides = true)
    static class TestModule {
    }

    @Inject
    AnalyticsServiceImpl analyticsServiceImpl;
    @Inject
    MeasureServiceImpl measureService;
    @Inject
    Context mContext;
    @Inject
    LoginService mLoginService;

    @Captor
    ArgumentCaptor<HashMap<String, Object>> data;

    @Captor
    ArgumentCaptor<String[]> varargs;

    private ArgumentCaptor<MeasurementViewEnum> enumArgumentCaptor;

    @Before
    public void setUp() throws Exception {
        Services.initialize(new AnalyticsServiceImplTest.TestModule()).inject(this);
        enumArgumentCaptor = ArgumentCaptor.forClass(MeasurementViewEnum.class);
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void trackSplashState_shouldReturnInstall_whenLaunchStatusEqualsINSTALL() throws Exception {
        analyticsServiceImpl = mock(AnalyticsServiceImpl.class);
        MeasureServiceMock measureServiceMock = new MeasureServiceMock();
        measureServiceMock.setStatus(MeasureServiceImpl.StartStatus.INSTALL);
        analyticsServiceImpl.mMeasureService = measureServiceMock;
        analyticsServiceImpl.trackSplashState(MeasurementViewEnum.SPLASH);
        verify(analyticsServiceImpl, times(1)).trackState(enumArgumentCaptor.capture(), data.capture());
    }
}

当我运行此测试用例时,在最后一行出现了空指针异常。我对单元测试有点陌生。您能解释一下我在这段代码中犯的错误吗?

1 个答案:

答案 0 :(得分:1)

1)您正在嘲笑无法正常工作的SUT:

analyticsServiceImpl = mock(AnalyticsServiceImpl.class);

您将验证其trackState方法,因此需要对其进行监视:

analyticsServiceImpl = spy(new AnalyticsServiceImpl());

2)您正在捕获输入,但是没有以任何方式声明它们。我想你错过了:

verify(analyticsServiceImpl, times(1)).trackState(enumArgumentCaptor.capture(), data.capture());
Map<String, Object> dataCaptured = data.getValue();
MeasurementViewEnum enumCapture = enumArgumentCaptor.getValue();

// assert these values

更新:

@Before
public void setUp() throws Exception {
   MockitoAnnotation.initMocks(this);
}