为了账号安全,请及时绑定邮箱和手机立即绑定

SQLException:当PowerMockito嘲笑Static DriverManager

SQLException:当PowerMockito嘲笑Static DriverManager

弑天下 2021-05-07 15:23:26
我正在尝试模拟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);” 因此,我一般不了解它的工作原理。
查看完整描述

2 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

当我创建objectUnderTest的实例并将其类名称放在@PrepareForTest批注下时,该解决方案最终会起作用(忽略out控制台中的警告)。尽管我不知道为什么会这样工作:


@RunWith(PowerMockRunner.class)

@PrepareForTest(DriverManager.class, MyClass.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.when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection);

  }


  @Test

  public void testMain() {

    // arrange

    String[] args = {"name", "password", "database"};

    MyClass myClass = new MyClass();

    myClass.method();

    ...

  }


查看完整回答
反对 回复 2021-05-26
  • 2 回答
  • 0 关注
  • 196 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信