使用Espresso测试RxJava2并在suscribeOn时获取空指针异常

ant*_*009 10 android unit-testing nullpointerexception android-espresso android-instrumentation

Android Studio 3.0 Beta2
Run Code Online (Sandbox Code Playgroud)

我正在测试使用RxJava2获取端点列表.该应用程序正常运行时工作正常.但是,当我使用espresso测试时,我尝试使用时会得到一个空指针异常subscribeOn(scheduler).对于调度程序,我使用trampoline()for subscribeOn和observeOn两个注入.

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'io.reactivex.Observable io.reactivex.Observable.subscribeOn(io.reactivex.Scheduler)' on a null object reference
Run Code Online (Sandbox Code Playgroud)

为了测试使用浓缩咖啡的RxJava2,有什么我应该做的,这对于subscribeOn和observeOn?

@Singleton
@Component(modules = {
        MockNetworkModule.class,
        MockAndroidModule.class,
        MockExoPlayerModule.class
})
public interface TestBusbyBakingComponent extends BusbyBakingComponent {
    TestRecipeListComponent add(MockRecipeListModule mockRecipeListModule);
}
Run Code Online (Sandbox Code Playgroud)

这是我的课程

public class RecipeListModelImp
        implements RecipeListModelContract {

    private RecipesAPI recipesAPI;
    private RecipeSchedulers recipeSchedulers;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Inject
    public RecipeListModelImp(@NonNull RecipesAPI recipesAPI, @NonNull RecipeSchedulers recipeSchedulers) {
        this.recipesAPI = Preconditions.checkNotNull(recipesAPI);
        this.recipeSchedulers = Preconditions.checkNotNull(recipeSchedulers);
    }

    @Override
    public void getRecipesFromAPI(final RecipeGetAllListener recipeGetAllListener) {
        compositeDisposable.add(recipesAPI.getAllRecipes()
                .subscribeOn(recipeSchedulers.getBackgroundScheduler()) /* NULLPOINTER EXCEPTION HERE */
                .observeOn(recipeSchedulers.getUIScheduler())
                .subscribeWith(new DisposableObserver<List<Recipe>>() {
                    @Override
                    protected void onStart() {}

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull List<Recipe> recipeList) {
                        recipeGetAllListener.onRecipeGetAllSuccess(recipeList);
                    }

                    @Override
                    public void onError(Throwable e) {
                        recipeGetAllListener.onRecipeGetAllFailure(e.getMessage());
                    }

                    @Override
                    public void onComplete() {}
                }));
    }

    @Override
    public void releaseResources() {
        if(compositeDisposable != null && !compositeDisposable.isDisposed()) {
            compositeDisposable.clear();
            compositeDisposable.dispose();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

调度程序的接口在这里,为了测试我正在使用注入的trampoline

@Module
public class MockAndroidModule {
    @Singleton
    @Provides
    Context providesContext() {
        return Mockito.mock(Context.class);
    }

    @Singleton
    @Provides
    Resources providesResources() {
        return Mockito.mock(Resources.class);
    }

    @Singleton
    @Provides
    SharedPreferences providesSharedPreferences() {
        return Mockito.mock(SharedPreferences.class);
    }

    @Singleton
    @Provides
    RecipeSchedulers provideRecipeSchedulers() {
        return new RecipeSchedulers() {
            @Override
            public Scheduler getBackgroundScheduler() {
                return Schedulers.trampoline();
            }

            @Override
            public Scheduler getUIScheduler() {
                return Schedulers.trampoline();
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

RecipleAPI的模拟模块

@Module
public class MockNetworkModule {
    @Singleton
    @Provides
    public RecipesAPI providesRecipeAPI() {
        return Mockito.mock(RecipesAPI.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是组件的创建方式

public class TestBusbyBakingApplication extends BusbyBakingApplication {
    private TestBusbyBakingComponent testBusbyBakingComponent;
    private TestRecipeListComponent testRecipeListComponent;

    @Override
    public TestBusbyBakingComponent createApplicationComponent() {
        testBusbyBakingComponent = createTestBusbyBakingComponent();
        testRecipeListComponent = createTestRecipeListComponent();

        return testBusbyBakingComponent;
    }

    private TestBusbyBakingComponent createTestBusbyBakingComponent() {
        testBusbyBakingComponent = DaggerTestBusbyBakingComponent.builder()
                .build();

        return testBusbyBakingComponent;
    }

    private TestRecipeListComponent createTestRecipeListComponent() {
        testRecipeListComponent = testBusbyBakingComponent.add(new MockRecipeListModule());
        return testRecipeListComponent;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于expresso测试,我正在做以下事情:

@RunWith(MockitoJUnitRunner.class)
public class RecipeListViewAndroidTest {
    @Inject RecipesAPI recipesAPI;

    @Mock RecipeListModelContract.RecipeGetAllListener mockRecipeListener;

    @Rule
    public ActivityTestRule<MainActivity> mainActivity =
            new ActivityTestRule<>(
                    MainActivity.class,
                    true,
                    false);

    @Before
    public void setup() throws Exception {
        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
        BusbyBakingApplication busbyBakingApplication =
                (BusbyBakingApplication)instrumentation.getTargetContext().getApplicationContext();

        TestBusbyBakingComponent component = (TestBusbyBakingComponent)busbyBakingApplication.createApplicationComponent();
        component.add(new MockRecipeListModule()).inject(this);
    }

    @Test
    public void shouldReturnAListOfRecipes() throws Exception {
        List<Recipe> recipeList = new ArrayList<>();
        Recipe recipe = new Recipe();
        recipe.setName("Test Brownies");
        recipe.setServings(10);
        recipeList.add(recipe);

        when(recipesAPI.getAllRecipes()).thenReturn(Observable.just(recipeList));
        doNothing().when(mockRecipeListener).onRecipeGetAllSuccess(recipeList);

        mainActivity.launchActivity(new Intent());

        onView(withId(R.id.rvRecipeList)).check(matches(hasDescendant(withText("Test Brownies"))));
    }
}
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪:

at me.androidbox.busbybaking.recipieslist.RecipeListModelImp.getRecipesFromAPI(RecipeListModelImp.java:37)
at me.androidbox.busbybaking.recipieslist.RecipeListPresenterImp.retrieveAllRecipes(RecipeListPresenterImp.java:32)
at me.androidbox.busbybaking.recipieslist.RecipeListView.getAllRecipes(RecipeListView.java:99)
at me.androidbox.busbybaking.recipieslist.RecipeListView.onCreateView(RecipeListView.java:80)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:607)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
at android.support.test.runner.MonitoringInstrumentation.callActivityOnStart(MonitoringInstrumentation.java:544)
at android.app.Activity.performStart(Activity.java:6268)
Run Code Online (Sandbox Code Playgroud)

非常感谢任何建议,

azi*_*ian 6

您的代码库中存在许多问题.但首要的是:你以某种方式实例化新的真实物体(而不是嘲笑),这就是你获得NPE的原因,与此无关subscribeOn().

  1. 您应该从生产组件扩展测试组件.目前它不是.

    public interface TestRecipeListComponent extends RecipeListComponent {...}
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在你的测试应用程序类中,你正在混合回调,即你TestRecipeListComponent在createApplicationComponent回调中创建,但是你有另一个回调来做到这一点:createRecipeListComponent().

  3. 你应该没有模拟出在你的每一个一切MockRecipeListModule.只是模拟组件,你真的需要嘲笑.例如,如果你嘲笑RecipeAdapter,那你怎么期望回收者视图在屏幕上绘制任何东西?您只需要模拟数据源提供程序,在您的情况下RecipeApi.除此之外什么都不应该被嘲笑,这不是单元测试,这是仪器测试.

  4. 在RecipeListView#onCreate()您创建一个新的RecipeListComponent,而你应该不会,你应该从一开始该组件Application类,因为你已经创建它.这会对测试造成影响:您无法从那里控制依赖关系,因为它RecipeListView会忽略您从测试中更改的所有依赖关系,并将创建一个新组件,该组件将提供其他依赖关系,因此您的存根将不会返回您明确硬的数据在测试中编码(实际上它们甚至不会被调用,真正的对象将是).这正是您遇到问题的原因.

我已经修好了这一切.我已经到了你写的断言没有通过的地步.你应该麻烦继续这个,因为它与你正在使用的逻辑/架构相关联.

我在这里打开了一个拉请求.