问题描述
我正在尝试在libgdx游戏上进行junit测试,并且发现此线程非常有用:
I am trying to do junit testing on a libgdx game, and have found this thread to be very helpful: Unit-testing of libgdx-using classes
我有一个类似于以下内容的测试类:
I have a test class similar to the following:
public class BoardTest {
private static Chess game;
private static HeadlessApplication app;
@BeforeClass
public static void testStartGame() {
game = new Chess();
final HeadlessApplicationConfiguration config = new HeadlessApplicationConfiguration();
config.renderInterval = 1f/60; // Likely want 1f/60 for 60 fps
app = new HeadlessApplication(game, config);
}
@Test
public void testSetUpBoard() {
final boolean isFalse = false;
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
//do stuff to game
fail(); //see if the test will fail or not
}
});
}
}
当我运行此测试类时,它将运行testSetUpBoard()并通过,而不是像应该的那样失败.我相信,这样做的原因是,根据Gdx.app.postRunnable(),执行的代码位于单独的线程中.有什么方法可以与junit线程通信,以便完成上述测试?
When I run this test class, it runs testSetUpBoard() and passes, instead of failing like it should. The reason for this, I believe, is because the executed code is in a separate thread as per Gdx.app.postRunnable(). Is there any way that I can communicate back to the junit thread, so that I can complete my tests like described?
推荐答案
您可以等待线程完成,如下所示:
You can wait for the thread to finish like this:
private boolean waitForThread = true;
@Test
public void testSetUpBoard() {
final boolean isFalse = false;
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
//do stuff to game
waitForThread = false;
}
});
while(waitForThread) {
try {
Thread.sleep(10);
} catch(Exception e ) {
}
}
// fail or pass...
fail(); //see if the test will fail or not
}
这篇关于libgdx-单元测试-如何与应用程序线程通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!