learningMyWayThru learningMyWayThru - 9 months ago 56
Java Question

Mockito object as null

I am trying to write a unit test case using Mockito. Below is my sample code:

class A {

Attr1 attr1;
Attr2 attr2;

public boolean methodToBeTested(String str) {

Boolean status1 = attr1.doSomething();

TempObject temp = attr2.create();

Boolean result = anotherMethod() && temp.doAnotherThing();


boolean anotherMethod() {

return true;

My Test Class:

class ATest extends AbstractTestCase {

Attr1 attr1;

Attr2 attr2;

TempObject tempObj;

A obj; // This is not mocked

public void setup() {

obj = new A(attr1, attr2);

public void testMethodToBeTested() {





However I get Null Exception when it tries to execute
In the mock test I have also tried using
inplace of

However this does not help either.

Am I mocking the object tempObj incorrectly?

Answer Source

If you are using the @Mock annotations be sure to mark your class as using the MockitoJUnitRunner

public class Test {
    private Foo foo; // will be instantiated by the runner rather than left null in OP question