有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在模拟void方法时获取UnfinishedStubbingException

尝试使用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
        
}

共 (1) 个答案

  1. # 1 楼答案

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

    莫基托不喜欢你这样做

    替换:

    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以了解更多信息