我正在尝试模拟Static DriverManager.class并获取mockConnection,但是真正的静态void方法却称为getConnection。
测试类别:
@RunWith(PowerMockRunner.class)
@PrepareForTest(DriverManager.class)
public class MyClassTest {
@Before
public void setUp() throws Exception {
Connection connection = mock(Connection.class);
Statement statement = mock(Statement.class);
PowerMockito.mockStatic(DriverManager.class);
PowerMockito.doReturn(connection).when(DriverManager.class, "getConnection", anyString(), anyString(), anyString());
}
@Test
public void testMain() {
// arrange
String[] args = {"name", "password", "database"};
}
}
Pom.xml
<properties>
<powermock.version>1.7.4</powermock.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
尝试执行PowerMockito.doReturn(connection).when(DriverManager.class,“ getConnection”,anyString(),anyString(),anyString())时遇到的异常:
java.sql.SQLException: No suitable driver found for
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1846)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:810)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:790)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:466)
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:110)
at vez.MyClassTest.setUp(MyClassTest.java:26)
我怎么了如何正确模拟DriverManager.class?
PS。当我查看org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:110)时,我看到它总是调用“ Whitebox.invokeMethod(classMock,methodToExpect,parameters);”因此,我不了解它通常如何工作。
最佳答案
DriverManager
类将尝试加载"jdbc.drivers"
系统属性中引用的驱动程序类,作为其初始化的一部分。当加载DriverManager
类时,即在调用getConnection()
之类的任何方法之前,都会发生这种情况。因此,并不是您得到的异常是因为调用了真实的getConnection()
。这是因为您没有在类路径中包含真实的驱动程序类,如pom
所示,DriverManager
可以在初始化期间加载。因此,在您的pom
中包含一个驱动程序,然后尝试。
请在https://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html处查看DriverManager类的源代码中的https://github.com/JetBrains/jdk8u_jdk/blob/master/src/share/classes/java/sql/DriverManager.java和static
块。