2016-11-02 2 views
1

Ich versuche, einen Unit-Testfall mit Mockito zu schreiben. Unten ist mein Beispielcode:Mockito-Objekt als Null

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-Klasse:

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)) 

    } 
} 

Jedoch habe ich Null Ausnahme erhalten, wenn es temp.doAnotherThing() auszuführen versucht. Im Scheintest habe ich auch versucht, Mockito.doReturn(tempObj).when(obj.attr2).create() anstelle von Mockito.when(obj.attr2.create()).thenReturn(tempObj)

zu verwenden, aber das hilft auch nicht.

Spotte ich das Objekt tempObj falsch?

+0

Sie meinen 'tempObj'? –

+0

Ja. Ich habe das mocked Objekt als tempObj in der Testklasse und als temp in der tatsächlichen Klasse genannt. – learningMyWayThru

Antwort

1

Wenn Sie verwenden die @Mock Anmerkungen sollten Sie Ihre Klasse zu markieren, wie unter Verwendung der MockitoJUnitRunner:

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