单元测试中的RxJava Schedules.io()NullPointerException

时间:2016-04-12 20:24:12

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

我试图在标准的JUnit测试中测试这个类,但是,我正在使用Schedulers.io()挂起NullPointerException。可以嘲笑Schedulers.io()吗?

这是一个Android应用程序,我试图使用travis-ci进行持续集成,并使用coveralls.io报告覆盖范围,对代码进行全面覆盖。

要测试的类:

$( document ).ajaxStop(function() {
  //All Ajax requests finished, call your function here...
  //You can also safely bind to and access the faceted search elements now. 
});

测试类:

public class GetLiveStreamsList extends UseCase {

    private final String filename;
    private final ContentRepository contentRepository;

    public GetLiveStreamsList( final String filename, final ContentRepository contentRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread ) {
        super( threadExecutor, postExecutionThread );

        this.filename = filename;
        this.contentRepository = contentRepository;

    }

    @Override
    protected Observable buildUseCaseObservable() {

        Action1<List<LiveStreamInfo>> onNextAction = new Action1<List<LiveStreamInfo>>() {

            @Override
            public void call( List<LiveStreamInfo> liveStreamInfos ) {

                try {
                    Thread.sleep( 5000 );
                } catch( InterruptedException e ) { }

            }

        };

        return this.contentRepository.liveStreamInfos( this.filename )
                .repeat( Schedulers.io() )
                .doOnNext( onNextAction );
    }

}

这是stacktrace:

public class GetLiveStreamsListTest {

    private static final String FAKE_FILENAME = "fake filename";

    private GetLiveStreamsList getLiveStreamsList;

    @Mock
    private ThreadExecutor mockThreadExecutor;

    @Mock
    private PostExecutionThread mockPostExecutionThread;

    @Mock
    private ContentRepository mockContentRepository;

    @Before
    public void setUp() {

        MockitoAnnotations.initMocks( this );
        getLiveStreamsList = new GetLiveStreamsList( FAKE_FILENAME, mockContentRepository, mockThreadExecutor, mockPostExecutionThread );

    }

    @Test
    public void testGetLiveStreamsListUseCaseObservableHappyCase() {

        getLiveStreamsList.buildUseCaseObservable();

        verify( mockContentRepository ).liveStreamInfos( FAKE_FILENAME );
        verifyNoMoreInteractions( mockContentRepository );
        verifyZeroInteractions( mockThreadExecutor );
        verifyZeroInteractions( mockPostExecutionThread );

    }

}

1 个答案:

答案 0 :(得分:3)

您忘记设置contentRepository.liveStreamInfos的返回值。它默认为null

您需要像这样设置返回值:

when(contentRepository.liveStreamInfos()).thenReturn(...);