我正在尝试模拟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>
我怎么了 如何正确模拟DriverManager.class?PS。当我查看org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:110)时,我看到它总是调用“ Whitebox.invokeMethod(classMock,methodToExpect,parameters);” 因此,我一般不了解它的工作原理。
侃侃无极
相关分类