0

首先,我很抱歉询问源代码。

MOCK静态方法的最简单方法是什么?

互联网上提供的所有建议都因初始化而失败

包 com.example.demo;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static String getHostname() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostName();
    }

    public static boolean getValid() throws UnknownHostException {
        System.out.println(getHostname());
        return false;
    }
    DemoApplication() {
        
    }
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

在上面的源代码中,我想测试 getValid() 方法,同时模拟 getHostName()

4

1 回答 1

0

Jmockit解决方案:

public Class DemoApplicationTest {
@Tested
public DemoApplication app;

@Test
public void testGetValid() {

  new Expectations(app) {{
    DemoApplication.getHostname();
    times=1;
    result = "example.org";
  }};

  final boolean res = DemoApplication.getValid();
  assertFalse(res);
}
于 2020-07-26T05:51:17.493 回答