简体   繁体   English

番石榴EventBus单元测试

[英]Guava EventBus unit tests

I have a simple Guava EventBus with one simple event and one simple listener. 我有一个简单的Guava EventBus,有一个简单的事件和一个简单的监听器。 My question is what is the test pattern to check if the listener method is invoked once the event is posted. 我的问题是检查一旦事件发布后是否调用了侦听器方法的测试模式是什么。

I would suggest that testing that the EventBus works properly is not a UNIT test you should be writing. 我建议测试EventBus正常工作不是你应该编写的UNIT测试。 One of the advantages of using a library (at least of using one you trust) is that the unit tests have been written by the library provider. 使用库(至少使用您信任的库)的一个优点是单元测试是由库提供程序编写的。 So please don't waste your time verifying that the Google folks wrote EventBus properly. 因此,请不要浪费时间来验证Google员工是否正确编写了EventBus。 To write unit tests of your system the EventBus should be mocked and therefore your listener would not be invoked. 要编写系统的单元测试,应该模拟EventBus,因此不会调用您的监听器。 This is one of the advantages of using a message bus, it allows for isolation of separate application concerns which allows for easier unit testing. 这是使用消息总线的优点之一,它允许隔离单独的应用程序问题,从而允许更容易的单元测试。

When you are ready to do so, it would be an integration test that tests that the entire system works together. 当您准备这样做时,它将是一个集成测试,测试整个系统是否一起工作。 In some cases this might also be written in JUnit but don't think that it is a unit test. 在某些情况下,这也可能是用JUnit编写的,但不认为它是单元测试。 How to do this depends on your system. 如何做到这一点取决于您的系统。 You might load up a Spring context into a JUnit test or you might deploy the application and run tests against it. 您可以将Spring上下文加载到JUnit测试中,也可以部署应用程序并针对它运行测试。

This kind of testing is usually done by using a mocking framework like Mockito . 这种测试通常使用像Mockito这样的模拟框架来完成。 Create a mock listener, register it with the event bus, fire the event, and verify that the listener method got invoked. 创建一个模拟侦听器,使用事件总线注册它,触发事件,并验证是否已调用侦听器方法。

Find here a very basic example on how to create a mock and how to verify interactions to it. 在这里找到一个关于如何创建模拟以及如何验证模拟交互的非常基本的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM