Unit Test EventBus on Android

1.1k Views Asked by At

I've already seen this SO question but yet it does not provide a solution to what I'm trying to do.

I'm using EventBus (from greenrobot) to send messages across my app. I'd like to be able to unit-test my app to confirm that a message have been posted to the bus. Just that.

Here's the class I'd like to test with a single method that post a message:

public class CxManager {
    public void postMessage(JsonObject data) {
        EventBus.getDefault().post(new MyCustomEvent(data));
    }
}

And here's the test I've tried but does not work:

@RunWith(MockitoJUnitRunner.class)
public class CxManagerTest {

    @Mock EventBus eventBus;
    private CxManager cxManager;
    private JsonObject testJsonObject;

    @Before public void setUp() throws Exception {
        cxManager = new CxManager();

        testJsonObject = new JsonObject();
        testJsonObject.addProperty("test", "nada");
    }

    @Test public void shouldPass() {
        cxManager.postMessage(testJsonObject);

        verify(eventBus).post(new MyCustomEvent(testJsonObject));
    }
}

I've written this test even knowing that it was likely to fail because EventBus uses a Singleton to post messages and I don't know how to test a singleton method being executed.

Also, this is just a piece of a large project. The relevant pieces. And I'd like to test the correct posting of messages according to different interactions

1

There are 1 best solutions below

6
Gabe Sechan On BEST ANSWER

Your problem is that the event bus the CxManager is posting to isn't your mock object. You'd have to reorganize your code to pass the EventBus into CxManager, either directly or via dependency injection, so that it posts to that eventBus rather than however its getting one now.

Alternatively, get an instance of the EventBus its actually posting to, and subscribe to it. THere's no need to actually mock EventBus here.