简体   繁体   中英

libgdx - junit testing - how do I communicate with the Application thread?

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

            }
        });
    }
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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