我是 Java 世界的新手,但很难理解为什么我不能对模拟对象进行 stub 方法...
@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();
}
}
当我尝试 stub getZIPStatistics() 方法时,我总是得到一个空指针异常,当然我得到了,因为在 getZIPStatistics() 方法中有一个私有(private)对象,它没有被模拟......在我看来Mockito 不会 mock 私有(private)字段...不幸的是,这是来自另一个项目:
public class BaseIT {
@Mock
protected static FromOtherProject engineMock;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
}
这里我模拟了引擎变量,但是如何模拟/ stub getZIPStatistics() 方法?这是这个方法:
public class FromOtherProject {
//...
public final String getZIPStatistics() {
return ZIPStatistics.toString();
}
}
我能做什么?
最佳答案
让我们假设一个简单的类...
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 等注释也会在父类(super class)中查找,因此您将获得模拟帐户,并且该帐户将被放入您的 AccountHolder 中。无需调用MockitoAnnotations.initMocks
。它不应该有什么坏处,但也不是必需的,因为您已经在使用 MockitoJUnitRunner
,它正是这样做的。
关于java - Mockito - 不可能 stub 模拟对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35487583/