【问题标题】:Getting UnfinishedStubbingException while mocking void method在模拟 void 方法时获取 UnfinishedStubbingException
【发布时间】: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 用更多信息更新了问题

标签: java mockito junit4


【解决方案1】:

您将模拟嵌套在模拟中。在完成服务的模拟之前,您正在调用 getDBConnection(),它会进行一些模拟。

Mockito 不喜欢你这样做。

替换:

try {
        
        when(mockDatabase.getDBConnection()).thenReturn(conn);
        Mockito.doNothing().when(service).deleteKeyInfo(mockDatabase.getDBConnection(), userBn, 1, "1");
    }

与:

try {
        
        when(mockDatabase.getDBConnection()).thenReturn(conn);
        some_variable_name =  mockDatabase.getDBConnection();         
        Mockito.doNothing().when(service).deleteKeyInfo(some_variable_name, userBn, 1, "1");
    }

请查看:Unfinished Stubbing Detected in Mockito 了解更多信息

【讨论】:

  • 2 个小 cmets: 1. 您不需要临时变量,只需使用 conn。 2 作为替代方案,Mockito.doNothing 是 void 方法的默认值,可以丢弃整个调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多