4
在我的应用程序中,我使用observer模式进行某些操作,我想在单元测试中对它们进行测试。问题是我不知道如何使用junit/mockito /别的东西来测试观察者。任何帮助?Junit/Mockito - 等待方法执行
例如,这是我的单元测试:
@Before
public void setUp() throws IOException, Exception {
observer = new GameInstanceObserver(); // observable (GameInstance) will call update() method after every change
GameInstance.getInstance().addObserver(observer); // this is observable which is updated by serverService
}
@Test(expected = UserDataDoesntExistException.class)
public void getRoomUserData_usingNullKey_shouldThrowUserDataDoesntExist() throws InterruptedException, UserDataDoesntExistException {
serverService.createRoom("exampleRoom"); // this operation is asynchronous and updates GameInstance data (as I wrote before GameInstance is Observable)
Thread.sleep(400); // how to do it in better way?
GameInstance gi = (GameInstance) observer.getObservable();
assertTrue(gi.getRoom("exampleRoom").getRoomId().equals("exampleRoom"));
}
我想不使用Thread.sleep()
并以这种方式使用它(或类似):
@Test(expected = UserDataDoesntExistException.class)
public void getRoomUserData_usingNullKey_shouldThrowUserDataDoesntExist() throws InterruptedException, UserDataDoesntExistException {
serverService.createRoom("exampleRoom"); // this operation is asynchronous and updates GameInstance data (as I wrote before GameInstance is Observable)
waitUntilDataChange(GameInstance.getInstance()); // wait until observable will be changed so I know that it notified all observer and I can validate data
GameInstance gi = (GameInstance) observer.getObservable();
assertTrue(gi.getRoom("exampleRoom").getRoomId().equals("exampleRoom"));
}
谢谢!有用! – pepuch
仅供参考,在GitHub中有一个CountDownLatchAnswer被设计用于此目的:https://github.com/dancerjohn/LibEx/blob/master/testlibex/src/main/java/org/libex/test/mockito/answer /CountDownLatchAnswer.java –
@JohnB,谢谢。我在哪里可以阅读关于这个LibEx库的更多信息?如何使用它,它创建了什么等等? – pepuch