我已经看到了这个 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 使用单例来发布消息,而我不知道如何测试正在执行的单例方法。
而且,这只是一个大项目的一部分。相关的部分。我想根据不同的交互来测试消息的正确发布