alwaysAStudent
alwaysAStudent

Reputation: 2274

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 {

    @Mock
    Attr1 attr1;

    @Mock
    Attr2 attr2;

    @Mock 
    TempObject tempObj;


    A obj;       // This is not mocked

    @Before
    public void setup() {

           obj = new A(attr1, attr2);
    }


    @Test
     public void testMethodToBeTested() {

           Mockito.when(obj.attr1.doSomething()).thenReturn(true);
           Mockito.when(obj.attr2.create()).thenReturn(tempObj);

           Mockito.when(tempObj.doAnotherThing()).thenReturn(true);

           Assert.assertTrue(obj.methodToBeTested(someString))

     }
}

However I get Null Exception when it tries to execute temp.doAnotherThing(). In the mock test I have also tried using Mockito.doReturn(tempObj).when(obj.attr2).create() inplace of Mockito.when(obj.attr2.create()).thenReturn(tempObj)

However this does not help either.

Am I mocking the object tempObj incorrectly?

Upvotes: 1

Views: 1329

Answers (1)

Ashley Frieze
Ashley Frieze

Reputation: 5443

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

@RunWith(MockitoJUnitRunner.class)
public class Test {
    @Mock
    private Foo foo; // will be instantiated by the runner rather than left null in OP question

Upvotes: 2

Related Questions