【问题标题】:Mockito object as nullMockito 对象为空
【发布时间】:2016-11-02 21:49:34
【问题描述】:

我正在尝试使用 Mockito 编写单元测试用例。下面是我的示例代码:

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;
  }
}

我的测试班:

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

     }
}

但是,当它尝试执行 temp.doAnotherThing() 时,我得到空异常。 在模拟测试中,我还尝试使用 Mockito.doReturn(tempObj).when(obj.attr2).create() 代替 Mockito.when(obj.attr2.create()).thenReturn(tempObj)

但这也无济于事。

我是否错误地模拟了对象 tempObj?

【问题讨论】:

  • 你的意思是tempObj?
  • 是的。我在测试类中将模拟对象命名为 tempObj,在实际类中命名为 temp。

标签: java unit-testing mocking mockito


【解决方案1】:

如果您使用@Mock 注释,请务必将您的课程标记为使用MockitoJUnitRunner

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    相关资源
    最近更新 更多