本文介绍了验证 rxjava 订阅者中的交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MVP 模式中描绘您的演示者订阅返回观察者的服务的情况:

Picture the situation in an MVP pattern where your presenter subscribes to a service returning an observer:

public void gatherData(){
   service.doSomeMagic()
      .observeOn(Schedulers.io())
      .subscribeOn(AndroidSchedulers.mainThread())
      .subscribe(new TheSubscriber());
}

现在类 TheSubscriber 从视图中调用 onNext 一个方法,比如:

Now the class TheSubscriber calls onNext a method from the view, say:

@Override public void onNext(ReturnValue value) {
  view.displayWhatever(value);
}

现在,在我的单元测试中,我想验证在非错误情况下调用方法 gatherData() 时,视图的方法 displayWhatever(value) 被调用.

Now, in my unit test I would like to verify that when the method gatherData() is called on a non-erroneous situation, the view's method displayWhatever(value) is called.

问题:

有没有干净的方法来做到这一点?

Is there a clean way to do this?

背景:

  • 我正在使用 mockito 来验证交互,当然还有更多
  • Dagger 正在注入除 TheSubscriber
  • 之外的整个 Presenter
  • I'm using mockito to verify the interactions and a lot more of course
  • Dagger is injecting the entire presenter except for TheSubscriber

我尝试了什么:

  • 注入订阅者并在测试中模拟它.我觉得有点脏,因为如果我想改变演示者与服务交互的方式(说不是 Rx),那么我需要改变很多测试和代码.
  • 模拟整个服务.这还不错,但需要我模拟很多方法,但我并没有完全达到我想要的效果.
  • 在互联网上四处查找,但似乎没有人有一种干净直接的方法来做到这一点

感谢您的帮助

推荐答案

假设您正在以类似的方式使用 serviceview 的接口:

Assuming that you are using interfaces for service and view in a similar manner:

class Presenter{
  Service service;
  View view;

  Presenter(Service service){
    this.service = service;
  }

  void bindView(View view){
    this.view = view;
  }

  void gatherData(){
    service.doSomeMagic()
      .observeOn(Schedulers.io())
      .subscribeOn(AndroidSchedulers.mainThread())
      .subscribe(view::displayValue);
  }
}

然后可以提供模拟来控制和验证行为:

It is possible then to provide mock to control and verify behaviour:

@Test void assert_that_displayValue_is_called(){
  Service service = mock(Service.class);
  View view = mock(View.class);
  when(service.doSomeMagic()).thenReturn(Observable.just("myvalue"));
  Presenter presenter = new Presenter(service);
  presenter.bindView(view);

  presenter.gatherData();

  verify(view).displayValue("myvalue");
}

这篇关于验证 rxjava 订阅者中的交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 03:41