0

This is my code:

@Mock
MyApplication application;

@Before
public void setup() {
    application = Mockito.mock(MyApplication .class);
}

@Test
public void createProducts() {

    application.ormLiteDatabaseHelper.getProductDao().create(new Product());
}

I get a NullPointerException at this line. My Application class inits the OrmLiteDatabaseHelper in its onCreate, how do I access the ormLiteDatabaseHelper from the mocked version of MyApplication?

Kaloyan Roussev
  • 14,515
  • 21
  • 98
  • 180

1 Answers1

2

application is a "mock" object. It only pretents to be a "MyApplication". Thus the only thing it can return for the method ormLiteDatabaseHelper is null and thus calling getProductDao on that will fail with a NullPointerException.

If you want it to return anything, then you need to tell your mock that, for example by...

OrmLiteDatabaseHelper ormLiteDatabaseHelper = ..something...;

Mockito.when( application.ormLiteDatabaseHelper ).thenReturn ( ormLiteDatabaseHelper);

Only then will your mock know to return something else than null. Of course, there are other ways, but for starters... Perhaps you also need partial mocking, which would be explained here, but without further info, it's hard to say.

Also, if you write @Mock, then you should either use the correct @RunWith annotation or call MockitoAnnotations.initMocks(this); instead of creating the mock manually via Mockito.mock. If you want to use the later, you don't need the @Mock annotation.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
  • could you also take a look at this question: http://stackoverflow.com/questions/34414018/cannot-instantiate-ormlite-helper-in-a-unit-test-class-in-android-studio THANKS – Kaloyan Roussev Dec 22 '15 at 23:04