Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MockitoAnnotations.initMocks crash while mock() succeeds

I'm having troubles using @Mock annotation with my instrumentation test.

Here's my gradle dependencies:

androidTestCompile 'org.mockito:mockito-core:1.10.19'
androidTestCompile 'com.google.dexmaker:dexmaker:1.2'
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2'

Here's a sample piece of code:

@Mock View mockView

@Before
public void setup() {
    MockitoAnnotation.initMocks(this);
    ...
}

This crashes with

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at com.google.dexmaker.mockito.DexmakerMockMaker.getInvocationHandlerAdapter(DexmakerMockMaker.java:80)
at com.google.dexmaker.mockito.DexmakerMockMaker.getHandler(DexmakerMockMaker.java:75)
...

However, this works

View mockView

@Before
public void setup() {
    mockView = Mockito.mock(View.class);
    ...
}

Anyone has any ideas what's going on here?

like image 817
Jin Avatar asked Aug 27 '15 23:08

Jin


People also ask

Is MockitoAnnotations initMocks deprecated?

initMocks. Deprecated. Use openMocks(Object) instead. This method is equivalent to openMocks(testClass).

What does MockitoAnnotations initMocks this ); do?

MockitoAnnotations. initMocks(this); initializes fields annotated with Mockito annotations. Allows shorthand creation of objects required for testing. Minimizes repetitive mock creation code.

Is initMocks needed?

initMocks(Object) is not necessary. Mocks are initialized before each test method. The first solution (with the MockitoAnnotations. initMocks ) could be used when you have already configured a specific runner ( SpringJUnit4ClassRunner for example) on your test case.

Which method in the Mockito API should be called to initialize the mocks?

initMocks( this ); This initializes objects annotated with Mockito annotations for given testClass. This method is useful when you have a lot of mocks to inject.


2 Answers

Its a bug in dexmaker. I have submitted a pull request to fix: https://github.com/crittercism/dexmaker/pull/24

Note that you may be able to work around it by avoiding null member variables in your test class.

like image 64
Andy Piper Avatar answered Oct 26 '22 15:10

Andy Piper


I've created an issue there https://github.com/mockito/mockito/issues/392

really bad hotfix:

try {
  MockitoAnnotations.initMocks(this);
} catch (NullPointerException e) {
  //waiting for fix
}
like image 37
Vova K. Avatar answered Oct 26 '22 13:10

Vova K.