Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit-testing of libgdx-using classes

I'm writing a game over libgdx; I'm using the junit framework to simplify unit-testing my code. Now there's part of the code (a map generator, a class converting my own map format into TiledMap...) which I need to test thoroughly, but it uses libgdx code: from file handling to asset loading. I'm not planning to test the actual graphical output, or the game itself, in this way: but I want to test the single components (calculation, asset access...) to avoid blatant errors.

I've tried to do something like this in the "setUpBeforeClass" method:

    LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
    cfg.useGL20 = true;
    cfg.width = 480;
    cfg.height = 320;
    cfg.resizable = true;
    LwjglApplication app = new LwjglApplication( new TestApplicationListener(), cfg);

And calling within tearDownAfterClass():

    Gfx.app.exit()

But it does create a window I do not need, and seems overkill when all I need is the file handling initialized. Is there a better way to initialize the libGDX components without creating an entire application object? Thanks.

EDIT

Going back over it (thanks to Sam in the comments), I realize GL access is needed (loading assets requires it), but this approach does not seem to work: the graphic library does not seem to be initialized. GDX documentation hasn't helped. Any clue?

like image 956
Calimar41 Avatar asked Apr 10 '14 09:04

Calimar41


2 Answers

This question hasn't been answered and I am surprised nobody has pointed out the headless backend, which is ideal for this situation. Combine this with your favorite mocking library and you should be good to go.

public class HeadlessLauncher {
    public static void main(final String[] args) {
        final HeadlessApplicationConfiguration config = new HeadlessApplicationConfiguration();
        config.renderInterval = Globals.TICK_RATE; // Likely want 1f/60 for 60 fps
        new HeadlessApplication(new MyApplication(), config);
    }
}
like image 156
Jyro117 Avatar answered Nov 10 '22 03:11

Jyro117


As already showed there is a HeadlessApplication backend which gives you an initialized libGDX but has no OpenGL context. For working with OpenGL you indeed need the LwjglApplication backend which creates an OpenGL window.

If you have problems writing tests which rely on the OpenGL context keep in mind that OpenGL is only attached to the thread of your LwjglApplication which is not the tread of your tests. Your tests have to call Gdx.app.postRunnable(Runnable r) to access the thread with the OpenGl context.

You may want to use synchronized and CountDownLatch to pause the test while waiting for your application to execute the command.

like image 2
Sebastian Avatar answered Nov 10 '22 02:11

Sebastian