在我的应用程序中,我将观察者模式用于某些操作,并且我想在单元测试中对其进行测试。问题是我不知道如何使用 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"));
}