assertTrue gives NPE in JUnit Test, but file is not null

Math Dummy :

I have a simple JUnit test, where I check whether an image is null or not. The image exists and is inside my assets folder in a ui package.

Here's the test:

@Test
public void testCreate() throws Exception {
    assertTrue(Gdx.files.internal("ui/back.png").exists());
} 

This is the exception I get:

java.lang.NullPointerException
    at com.fantasticfeasts.game.Teamkofigeditor.FantasticFeastsGameTest.testCreate(FantasticFeastsGameTest.java:35)

How is that possible when the image exists and it's inside the ui folder?

JUnit test

Morchul :

In your example Gdx.files is null so there comes the NPE.

Your problem is that Gdx. tools are only available after you started an Application like LwjglApplication or HeadlessApplication from LibGdx.

Because first after you start an Application instance, LibGdx will load libraries and initialize: Gdx.app, Gdx.files, Gdx.graphics, Gdx.audio, Gdx.gl etc.

To test your LibGdx project whit Gdx features read this: http://manabreak.eu/java/2016/10/21/unittesting-libgdx.html

Here is an Example of Unit test with Gdx.files: https://github.com/TomGrill/gdx-testing/tree/master/tests/src/de/tomgrill/gdxtesting

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=100508&siteId=1