【发布时间】:2020-07-09 17:49:42
【问题描述】:
尝试使用 JUnit4 模拟 void 方法然后遇到异常
下面是类定义
@Mock
private TestService service;
@Mock
private DatabaseService mockDatabase;
@Before
public void setUpMock() throws Exception {
LOGGER.info("########### Moke setUp started ###########");
conn = Mockito.mock(Connection.class);
MockitoAnnotations.initMocks(this);
LOGGER.info("########### Moke setUp completed ###########");
}
@Test
public void testSuccess() {
try {
when(mockDatabase.getDBConnection()).thenReturn(conn);
Mockito.doNothing().when(service).deleteKeyInfo(mockDatabase.getDBConnection(), userBn, 1, "1");
} catch (Exception e) {
fail("### testDeviceIdNull ### Failed with following error: " + getStackTrace(e));
}
}
但低于异常
java.lang.AssertionError: ### Failed with following error: org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
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, which is not supported
3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed
下面是void方法
public void deleteKeyInfo(Connection conn, UserBn userBn, Integer smId, String dId) throws Exception {
// Deleting key
}
【问题讨论】:
-
我有一段时间没用过 Mockito,但我相信目前首选的风格是
when(service.deleteKeyInfo()).doNothing()。 (另外,我认为service.delete应该都在when内。) -
对于错误的根本原因,我们需要更多上下文:
service(模拟或间谍)doNothing()是模拟的 void 方法的默认操作。如果service是一个模拟,那么删除有问题的行会有所帮助。mockDatabase是什么?你如何指定mockDatabase.getDBConnection()的行为? -
@Lesiak 用更多信息更新了问题