Springboot, Powermockito, failing to mock static method

155 Views Asked by At

First, I apologize for asking source code.

What is the simplest way to MOCK static method?

All the suggestions that is provided all over the internet is failing with initialization

package 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);
    }

}

in the source code above, I want to test getValid() method, while mocking getHostName()

1

There are 1 best solutions below

0
On

Jmockit solution:

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);
}