在无头 LibGDX 单元测试中创建纹理 [英] Creating Texture in headless LibGDX unit tests

查看:23
本文介绍了在无头 LibGDX 单元测试中创建纹理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 LibGDX 无头后端 运行 jUnit 测试.这适用于某些测试,但如果我尝试创建 new Texture('myTexture.png');,我会得到 NullPointerException.确切的错误是:

I am using the LibGDX headless backend to run jUnit tests. This works well for certain tests, but if I try to create a new Texture('myTexture.png');, I get a NullPointerException. The exact error is:

java.lang.NullPointerException
    at com.badlogic.gdx.graphics.GLTexture.createGLHandle(GLTexture.java:207)

为了简单起见,我创建了一个除了加载纹理之外什么都不做的方法:

To keep things simple, I created a method that does nothing other than load a texture:

public class TextureLoader {
    public Texture load(){
        return new Texture("badlogic.jpg");
    }
}

然后,我的测试类如下所示:

Then, my test class looks like this:

public class TextureTest {

    @Before
    public void before(){
        final HeadlessApplicationConfiguration config = new HeadlessApplicationConfiguration();
        new HeadlessApplication(new ApplicationListener() {
            // Override necessary methods
            ...
        }, config);
    }

    @Test
    public void shouldCreateTexture() {
        TextureLoader loader = new TextureLoader();
        assertNotNull( loader.load() );
    }
}

这个方法在我的实际应用中可以正常工作,只是在单元测试中不行.

This method is working correctly in my actual app, just not in the unit tests.

如何使用 HeadlessApplication 类来加载纹理?

How can I use the HeadlessApplication class to load Textures?

推荐答案

模拟 Gdx.gl 帮助我解决了纹理创建期间的这个 NullPointerException:

Mocking the Gdx.gl help me solved this NullPointerException during Texture creation:

import static org.mockito.Mockito.mock;

...

Gdx.gl = mock(GL20.class);

我将它与 GdxTestRunner 一起使用,请参阅 https://bitbucket.org/TomGrill/libgdx-测试样本

I used it with GdxTestRunner, see https://bitbucket.org/TomGrill/libgdx-testing-sample

public GdxTestRunner(Class<?> klass) throws InitializationError {
    super(klass);
    HeadlessApplicationConfiguration conf = new HeadlessApplicationConfiguration();
    new HeadlessApplication(this, conf);
    Gdx.gl = mock(GL20.class); // my improvement
}

这篇关于在无头 LibGDX 单元测试中创建纹理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆