How to/Should I unit test EventBus events with Mockito?

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

I use Otto's EventBus in my Android app.

In my LoginNetworkOperation class, I catch different kinds of network connection errors and I post different bus events for each one, and my LoginPresenter class is registered as a listener and certain methods are invoked, when these events are fired.

My question is how (and should I) do I unit test whether the LoginNetworkOperation throws this event and LoginPresenter handles it with Mockito?

I looked at this question: Guava EventBus unit tests but it doesn't provide enough information, especially on the implementation part.

public class LoginNetworkOperation {      public void execute(String username, String password) {         try {             // retrofit attempt         } catch (Exception e) {             bus.post(new ExceptionEvent(e));         }     } }  public class LoginPresenter {      void onExceptionEvent(ExceptionEvent exceptionEvent) {         // Do Something with the exception event     } } 

Also, which should be the Subject Under Test here and which should be the mocked object?

I am using JUnit + Mockito + Robolectric in Android Studio and my test artifact is Unit Tests

回答1:

My question is how (and should I) do I unit test whether the LoginNetworkOperation throws this event and LoginPresenter handles it with Mockito?

That's already an integration test: you're combining individual software modules and verifying their behaviour as a group.

In that case the "subject under test" is the combination of LoginNetworkOperation, EventBus and LoginPresenter and the mocked objects are the inputs to LoginNetworkOperation and whatever handles the output of LoginPresenter.


Those three software modules can also be unit tested:

  • LoginNetworkOperation.execute: mock the EventBus and verify that it's called with the correct ExceptionEvent for different inputs.
  • LoginPresenter.onExceptionEvent: verify correct behaviour for different ExceptionEvents.
  • EventBus.post: register a mocked ExceptionEvent-Handler, post an ExceptionEvent and check that the Handler is called.


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!