0

我已经看到了这个 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 使用单例来发布消息,而我不知道如何测试正在执行的单例方法。

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

4

1 回答 1

2

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

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

于 2018-09-10T12:14:53.547 回答