相关疑难解决方法(0)

用Mockito模拟静态方法

我写了一个工厂来生产java.sql.Connection物品:

public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {

    @Override public Connection getConnection() {
        try {
            return DriverManager.getConnection(...);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想验证传递给的参数DriverManager.getConnection,但我不知道如何模拟静态方法.我正在使用JUnit 4和Mockito来测试我的测试用例.有没有一种很好的方法来模拟/验证这个特定的用例?

java unit-testing mocking mockito

321
推荐指数
12
解决办法
61万
查看次数

是否可以使用 Mockito 模拟静态且无效的方法?

我试图避免在这里使用 PowerMockito。我们有遗留代码,其中包含静态和无效的方法,并且有一些测试需要模拟它们。有没有办法做到这一点,或者重构遗留代码是唯一的方法吗?

class MySample {
       public static void sampleMethod(String argument){
                //do something
       }
}
Run Code Online (Sandbox Code Playgroud)

如果我使用通用的 MockStatic 语法,它会要求我返回一些内容:

MockedStatic <MySample> sampleMock = Mockito.mockStatic( MySample.class );
sampleMock.when(() -> MySample.sampleMethod(Mockito.any(String.class)));
Run Code Online (Sandbox Code Playgroud)

例外:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at com.mytests.Test.setMock(Test.java:35)

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 …
Run Code Online (Sandbox Code Playgroud)

java mockito

5
推荐指数
1
解决办法
9137
查看次数

标签 统计

java ×2

mockito ×2

mocking ×1

unit-testing ×1