16 July, 2015

mocking is Null after @InjectMocks

Mocking is null after injecting the mock, this issue is very common in mockito. I faced this issue when trying to write the junit test case . 

This issue seems you need to load the test class using MockitoAnnotations.initMocks. Because , there is certain steps you need to do / setup the data before executing the test method.

@InjectMocks
    private TokenServiceFormatter tokenServiceFormatter ;


As above I have already injected the respective class, that I want to inject. But, while running its showing the tokenServiceFormatter  (injected object ) is null. So, inside the setup() method you need to load the test class as below.


    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);    
    }

 @Test
public void testMethod(){
//Do your test here
}




Happy Mockinggggggggggggg.



2 comments: