Mockito - 不可能存根嘲弄对象

时间:2016-02-18 16:51:28

标签: java unit-testing mocking mockito stub

我是Java世界的新手,但是很难理解为什么我不能将一个模拟对象的方法存根...

@RunWith(MockitoJUnitRunner.class)
public class ChildBLLIT extends BaseInteractorIT {

  @InjectMocks
  private ChildBLL ChildBLL = Mockito.mock(ChildBLL.class);

  @Before
  public void setUp() {
    ChildBLL.engine = engineMock;
  }

  /**
   * Test of getZipStatistics method, of class ChildBLL.
   */
  @Test
  public void testGetZipStatistics() {
    final String testZipStatisticsText = "DummyZipStatistics";
    //This method will throw the null pointer exception
   when(ChildBLL.engine.getZIPStatistics()).thenReturn(testZipStatisticsText);


    ChildBLL.getZipStatistics();
    verify(ChildBLL.engine).getZIPStatistics();
  }

}

当我尝试存根getZIPStatistics()方法时,我总是得到一个空指针异常,当然我得到了,因为在getZIPStatistics()方法中有一个私有对象,它没有被嘲笑......在我看来Mockito并没有嘲笑私人领域......不幸的是,这是来自另一个项目:

public class BaseIT {

  @Mock
  protected static FromOtherProject engineMock;

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

这里我模拟了引擎变量,但是我怎样才能模拟/存根getZIPStatistics()方法?这是这个方法:

public class FromOtherProject {
    //...
    public final String getZIPStatistics() {
        return ZIPStatistics.toString();
    }
}

我该怎么办?

1 个答案:

答案 0 :(得分:1)

让我们假设一个简单的课程......

public class Account {

    public String getPassword() {
        return "abc";
    }
}

...包含它的简单类......

public class AccountHolder {
    private Account account;

    public String getAccountPassword() {
         return this.account.getPassword();
    }

}

现在我们为所有基于帐户的测试提供了一个简单的基类...

public class AccountBasedTest {

   @Mock
   protected Account account;

}

...以及实际测试AccountHolder的类......

@RunWith(MockitoJUnitRunner.class)
public class AccountHolderTest extends AccountBasedTest {

    @InjectMocks
    private AccountHolder accountHolder;

    @Test
    public void getAccountPasswort_must_return_account_password() {
         Mockito.when( this.account.getPassword() ).thenReturn ("xyz");

         Assert.assertEquals("xyz", this.accountHolder.getAccountPassword());
    }

}

这就是全部。 @InjectMocks等注释也将在超类中查找,因此您将获得您的模拟帐户,该帐户将被放入您的AccountHolder。无需致电MockitoAnnotations.initMocks。它不应该受到伤害,但不需要它,因为你已经使用了MockitoJUnitRunner,这正是如此。