Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock java.net.NetworkInterface?

I am going to test a method that takes a List of java.net.NetworkInterface as argument, and so I should mock the final abstract class or instantiate it. Any idea about doing these?

The method is something like this:

public void handleInterfaces(List<NetworkInterface> interfaces){
    for(NetworkInterface interface : interfaces){
        //get interface mac address
        //get interface name
        //doSomething here;
    }
}

Writing a mockito-when for every getter method is kind of ugly, so I think I should write my own version of this POJO class with a constructor. Before doing that, I am wondering is there a better scheme to just do something like this:

NetworkInterface mockedInterface = instantiateTheInterface("eth1",192.168.1.1,theMacAddress);

I stick with the rule "don't use powermockito ever", so I just implemented a wrapper class and I think its the cleanest way:

public class NetworkInterfaceWrapper{
    private NetworkInterface networkInterface;
    public NetworkInterfaceWrapper(NetworkInterface networkInterface){
        this.networkInterface = networkInterface;
    }
    public String getName(){
        return networkInterface.getName();
    }
    ...and so on for all Getters i've used from NetworkInterface
}

Final Solution It turns out that there is another annoying Object in NetworkInterface, called InterfaceAddress which i should write another wrapper for that! So i am going to use shell commands to retrieve the mac address, net mask and interface name and gateway of host and i don't want to use NetworkInterface ever because with all of these restrictions they are just suggesting "You are not allowed to touch this"! P.S: I wonder why Oracle guys are obsessed with final abstract, i know that they know more than i do, but in this particular case of NetworkInterface, why final abstract? using a single comprehensive constructor would make the class, immutable too

like image 579
redbeard1970 Avatar asked Jan 01 '17 12:01

redbeard1970


1 Answers

You can use PowerMockito to mock java standard library final class.

For example;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ NetworkInterface.class })
public class NetworkInterfaceMocks {

@Test
public void sameClassSuccess() throws Exception {
    final NetworkInterface mockInterface = PowerMockito.mock(NetworkInterface.class);

    when(mockInterface.isUp()).thenReturn(true);
    assertTrue(mockInterface.isUp());
}

@Test
@PrepareForTest(OtherClass.class)
public void differentClassSuccess() throws Exception {
    final NetworkInterface mockInterface = PowerMockito.mock(NetworkInterface.class);

    when(mockInterface.isUp()).thenReturn(true);
    assertTrue(new OtherClass().isUp(mockInterface));
}

In my opinion it should be used only in very rare and non-avoidable cases.

like image 168
fabfas Avatar answered Nov 09 '22 22:11

fabfas