Unit-testing of libgdx-using classes

徘徊边缘 提交于 2019-12-03 13:19:56

问题


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?


回答1:


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);
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/22984129/unit-testing-of-libgdx-using-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!