samedi 4 mars 2017

How to properly initialize an android activity context for an instrumented test?

I have some troubles with android tests.

In every test I try to make, whether the test passes or not, at the end of the execution, I got this error Test running failed: Instrumentation run failed due to 'java.lang.NullPointerException'

I don't get why it always appear, I must made initialization mistakes but I can't figure out which ones ... For instance, this simple test give me the error, even thought the test passes :

public class PhysicsInitAndroidTest {

    // game stuff
    private List<Player> snakes;
    private List<Wall> walls;
    private List<MapItem> items;

    // test stuff
    private View view;
    private Context context;

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);



    @Before
    public void setUp(){
        context = InstrumentationRegistry.getTargetContext();
        snakes = new ArrayList<>();
        walls = new ArrayList<>();
        items = new ArrayList<>();
        System.setProperty("dexmaker.dexcache", context.getCacheDir().getPath());
        view = new View(context);
    }

    @Test
    public void generateSnakesTest(){
        assertEquals(snakes.size(), 0);

        for(int i = 0; i < 20; i++){
            snakes.add(PhysicsInit.generateSnake(i, i, view));
        }

        assertEquals(snakes.size(), 20);

        for(int i = 0; i < snakes.size(); i++){
            Player snake = snakes.get(i);
            assertEquals(snake.getClass(), Player.class);
            assertEquals(snake.getDirection().getX(), 0.0f, 0.001);
            assertEquals(snake.getDirection().getY(), 0.0f, 0.001);
        }
    }
}

How could I avoid such error ? thanks !

Aucun commentaire:

Enregistrer un commentaire