简体   繁体   English

在 mocking void 方法时出现 UnfinishedStubbingException

[英]Getting UnfinishedStubbingException while mocking void method

Trying mock void method using JUnit4 then getting below exception尝试使用 JUnit4 模拟 void 方法,然后遇到异常

Below is the class definition下面是 class 定义

@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));
    }
}

But getting below exception但低于例外

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

Below is the void method下面是void方法

public void deleteKeyInfo(Connection conn, UserBn userBn, Integer smId, String dId) throws Exception {
    // Deleting key
        
}

You're nesting mocking inside of mocking.您将 mocking 嵌套在 mocking 内。 You're calling getDBConnection(), which does some mocking, before you've finished the mocking for service.在您完成 mocking 服务之前,您正在调用 getDBConnection(),它会执行一些 mocking。

Mockito doesn't like it when you do this. Mockito 不喜欢这样做。

Replace:代替:

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

with:和:

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

Please check this: Unfinished Stubbing Detected in Mockito for more information请检查: 在 Mockito 中检测到未完成的存根以获取更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM