gpt4 book ai didi

java - Junit/Mockito - 等待方法执行

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:15:59 33 4
gpt4 key购买 nike

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

最佳答案

如果我没理解错的话,问题其实不是测试观察者,而是测试一个异步方法调用的结果。为此,创建一个观察器,它会阻塞直到调用其 update() 方法。类似于以下内容:

public class BlockingGameObserver extends GameInstanceObserver {
private CountDownLatch latch = new CountDownLatch(1);

@Override
public void update() {
latch.countDown();
}

public void waitUntilUpdateIsCalled() throws InterruptedException {
latch.await();
}
}

在你的测试中:

private BlockingGameObserver observer;

@Before
public void setUp() throws IOException, Exception {
observer = new BlockingGameObserver();
GameInstance.getInstance().addObserver(observer);
}

@Test
public void getRoomUserData_usingNullKey_shouldThrowUserDataDoesntExist() throws InterruptedException, UserDataDoesntExistException {
serverService.createRoom("exampleRoom");
observer.waitUntilUpdateIsCalled();
assertEquals("exampleRoom",
GameInstance.getInstance().getRoom("exampleRoom").getRoomId());
}

关于java - Junit/Mockito - 等待方法执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16636900/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com