单元测试Powermockito/Java间谍类以验证私有方法调用
我正在使用Mockito/PowerMockito用java编写单元测试,但在我正在进行的测试中,我无法摆脱这个未完成的Stubbing异常
我试图测试的方法是私有的,所以我使用WhiteBoxImpl来调用该方法。在我调用的方法中,可能会调用被测试类中的另一个私有方法(称为pm2)。我想验证pm2从未被调用,所以我为被测试的类做了一个间谍,并验证pm2从未被()调用
到目前为止,这个测试总是抛出一个未完成的StubbingException,但我不知道我的测试Powermockito不喜欢哪个部分。我还有另一个(正在运行的)测试,其操作非常类似,只是我不需要验证pm2之类的方法的行为。所以在这种情况下,我不需要为被测试的类创建间谍。我相信我的问题在某种程度上与间谍有关,但我不知道如何在没有它的情况下测试我要测试的东西
以下是我现在拥有的:
@Mock(name = "BO")
BO BOMock;
@Mock(name = "DAO")
DAOI DAOMock;
@InjectMocks
ServiceImpl service;
@Test
public void unitTest(){
MessageObject msg = new MessageObject();
Record recordMock = mock(Record.class);
MetaData metaDataMock = mock(MetaData.class);
doNothing().when(DAOMock).doAction(any(Param1.class), anyInt());
when(DAOMock.doOtherAction(any(Param1.class), eq(msg.getId()))).thenReturn(recordMock);
when(BOMock.getMetaData(anyInt(), anyInt()).thenReturn(metaDataMock);
ServiceImpl spy = PowerMockito.spy(this.service);
PowerMockito.doReturn(new Long(10)).when(spy, "checkDelay", recordMock, msg, metaDataMock);
Whitebox.invokeMethod(spy, "process", msg);
verify(recordMock, never()).getStatus();
}
下面是我正在测试的ServiceImpl类中的方法:
private BO BO = new BO();
private DAOI DAO = new DAO();
private void process(Message msg) {
try {
DAO.doAction(new Param1.class, msg.getId());
} catch(Exception e) {
logger.error("some message");
return;
}
Record record = null;
try {
int intParam1 = msg.getId();
int intParam2 = msg.getDifferentId();
MetaData metaData = BO.getMetaData(intParam1, intParam2);
record = DAO.loadRecord(new Param1(), msg.getId());
// checkDelay is a private method in ServiceImpl.java
long delayForMinutes = checkDelay(record, msg, metaData);
if(delayForMinutes > 0) {
// Control should reach here
logger.debug("some message");
return;
}
// Control should not reach here
if(Record != null && Record.getStatus() != CREATED) {
logger.debug("some message");
return;
}
// Perform various actions
} catch(Exception e) {
// Perform other various actions
}
}
当我运行这个测试时,我得到一个未完成的stubbing异常。堆栈跟踪顶部的行是:
DAO.doAction(new Param1.class, msg.getId());
错误消息提供了以下提示:
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
但我似乎不知道它们中的任何一个如何适用于我的情况。有人知道幕后发生了什么导致了这个错误吗
谢谢!
# 1 楼答案
问题是
这里似乎没有
then
、thenReturn
或thenThrow
。你总是需要使用其中一个带有when