如何使用java.net.InetAddress静态方法运行PowerMock v1.74

时间:2019-06-11 19:08:49

标签: java powermockito

我已经阅读了很多有关PowerMockito来模拟静态方法的内容。所以我一直在尝试使用v1(而不是v2),尽管我并不在乎我使用哪个版本的PowerMockito或testNG。我想我错过了配置中的一些关键细节,但我茫然。

使用Oracle Java 1.8

subprojects.gradle:

testCompile group: 'org.testng',                  name: 'testng',               version: '6.14.3'
testCompile group: 'org.powermock',           name: 'powermock-module-testng',  version: '1.7.4'
testCompile group: 'org.powermock',           name: 'powermock-api-mockito',    version: '1.7.4'

我检查了模块here的版本

测试类

import org.mockito.*;
import org.mockito.invocation.*;
import org.mockito.stubbing.*;
import org.powermock.core.classloader.annotations.*;
import org.powermock.modules.testng.*;
import org.testng.*;
import org.testng.annotations.*;

import java.io.*;
import java.net.*;

import static org.powermock.api.mockito.PowerMockito.*;

@PrepareForTest({java.net.InetAddress.class})
public class testClass extends PowerMockTestCase {
  @Test   
  public void exampleTest()
     throws IOException, URISyntaxException, MyCustomException {

    mockStatic(InetAddress.class);
    // I use these three functions, so I think I have to mock them all?
    when(InetAddress.getByName(Mockito.anyString()))
        .thenReturn(InetAddresses.forString("111.0.0.111"));    
    when(InetAddress.getByAddress(Mockito.anyObject()))
      .thenCallRealMethod();
    when(InetAddress.getLocalHost()).thenCallRealMethod();

    MyNewClass mnc = new MyNewClass();
    mnc.someCodeUsingInetAddress();
  }

当从someCodeUsingInetAddress()调用时,它将编译并运行,但不会更改InetAddress.getByName()函数的行为。

现在我读了here,我需要用该标签 @RunWith(PowerMockRunner.class)。但是IntelliJ不允许我从它知道的任何可能来源中导入PowerMockRunner.class。这也让我想知道我应该尝试使用哪个。

org.testng.PowerMockRunner
org.testng.annotations.PowerMockRunner
org.powermock.modules.testng.PowerMockRunner

列表继续...

0 个答案:

没有答案