Android上的单元测试EventBus

问题描述 投票:0回答:1

我已经看过this SO question,但它没有提供我想要做的解决方案。

我正在使用EventBus(来自greenrobot)在我的应用程序中发送消息。我希望能够对我的应用进行单元测试,以确认已将消息发布到总线上。只是。

这是我想用发布消息的单个方法测试的类:

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

这是我尝试但不起作用的测试:

@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));
    }
}

我写过这个测试,即使知道它可能会失败,因为EventBus使用Singleton发布消息,我不知道如何测试正在执行的单例方法。

此外,这只是一个大项目的一部分。相关部分。我想根据不同的交互测试正确的消息发布

android unit-testing mockito greenrobot-eventbus-3.0
1个回答
2
投票

您的问题是CxManager发布的事件总线不是您的模拟对象。您必须重新组织代码以将EventBus直接或通过依赖注入传递到CxManager,以便它发布到该eventBus而不是现在获得一个。

或者,获取它实际发布到的EventBus的实例,并订阅它。这里没有必要真正模拟EventBus。

© www.soinside.com 2019 - 2024. All rights reserved.