0

I have a problem with Robolectric. I'm trying to test an adapter I'm going to implement, and my first test should check if an adapter is instantiated and all the fields are created and ok.

In my adapter constructor I have this:

public MyAdapter(Context context) {
    this.mContext = context;
    this.mLayoutInflater =  LayoutInflater.from(mContext);
    this.listOfItems= new ArrayList<Items>();
}

and my Test looks like this

@Test
public void newInstanceNoDataSetTest(){
    //Initialize a new adapter and test if all the needed fields are created
    MyAdapter adapterNoDataSet = new MyAdapter(MyApp.getInstance().getApplicationContext());

    Assert.assertNotNull(adapterNoDataSet);
    testFields(adapterNoDataSet);

    //Check to see if the count of the adapter is 0 (no items have been set)
    Assert.assertEquals(adapterNoDataSet.getCount(),0);
}

Every time I run my test it fails with NullpointerException at this line this.mLayoutInflater = LayoutInflater.from(mContext); I think it has to do with the fact that that's a static call.

Can anybody help me with that?

Thanks, Ark

Aurelian Cotuna
  • 3,076
  • 3
  • 29
  • 49

1 Answers1

1

I think the issue probably comes from your usage of MyApp.getInstance(), which I assume points to your Application. When running the app normally, the Application will be created, so your instance won't be null. When running with Robolectric, on the other hand, the Application instance is created by Robolectric, and is accessible through RuntimeEnvironment.application, if you're using Robolectric 3.0 or Robolectric.application otherwise. Your code should look like this:

@Test
public void newInstanceNoDataSetTest(){
    //Initialize a new adapter and test if all the needed fields are created
    MyAdapter adapterNoDataSet = new MyAdapter((MyApp)RuntimeEnvironment.application);

    Assert.assertNotNull(adapterNoDataSet);
    testFields(adapterNoDataSet);

    //Check to see if the count of the adapter is 0 (no items have been set)
    Assert.assertEquals(adapterNoDataSet.getCount(),0);
}
J.C. Chaparro
  • 1,079
  • 10
  • 13