猿问

SQLException:当PowerMockito嘲笑Static DriverManager

我正在尝试模拟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);” 因此,我一般不了解它的工作原理。



弑天下
浏览 197回答 2
2回答

侃侃无极

当我创建objectUnderTest的实例并将其类名称放在@PrepareForTest批注下时,该解决方案最终会起作用(忽略out控制台中的警告)。尽管我不知道为什么会这样工作:@RunWith(PowerMockRunner.class)@PrepareForTest(DriverManager.class, MyClass.class)public class MyClassTest {&nbsp; @Before&nbsp; public void setUp() throws Exception {&nbsp; &nbsp; Connection connection = mock(Connection.class);&nbsp; &nbsp; Statement statement = mock(Statement.class);&nbsp; &nbsp; PowerMockito.mockStatic(DriverManager.class);&nbsp; &nbsp; PowerMockito.when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection);&nbsp; }&nbsp; @Test&nbsp; public void testMain() {&nbsp; &nbsp; // arrange&nbsp; &nbsp; String[] args = {"name", "password", "database"};&nbsp; &nbsp; MyClass myClass = new MyClass();&nbsp; &nbsp; myClass.method();&nbsp; &nbsp; ...&nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答