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



需要测试的方法 - 位于 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(你在嘲笑根本不起作用的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);
}

相关内容

  • 没有找到相关文章

最新更新