Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Texture in headless LibGDX unit tests

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.

How can I use the HeadlessApplication class to load Textures?

like image 930
twiz Avatar asked Sep 01 '14 20:09

twiz


1 Answers

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

import static org.mockito.Mockito.mock;

...

Gdx.gl = mock(GL20.class);

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
}
like image 190
Bill Lin Avatar answered Oct 23 '22 10:10

Bill Lin