How to simulate Java net. NetworkInterface?
I'll test one in Java net. The networkinterface list is used as a parameter method, so I should simulate the final abstract class or instantiate it
The method is as follows:
public void handleInterfaces(List<NetworkInterface> interfaces){ for(NetworkInterface interface : interfaces){ //get interface mac address //get interface name //doSomething here; } }
It's a bit ugly to write a mockito when for each getter method, so I think I should write my own version of this POJO class with a constructor Before that, I would like to know if there is a better plan to do such a thing:
NetworkInterface mockedInterface = instantiateTheInterface("eth1",192.168.1.1,theMacAddress);
I adhere to the rule of "never use powermockito", so I just implemented a wrapper class, which I think is 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 }
The final solution turns out that there is another annoying object in the network interface, called interfaceaddress, for which I should write another wrapper! So I will use the shell command to retrieve the MAC address, netmask, interface name and gateway of the host. I don't want to use networkinterface because of all these restrictions. They just suggest "you're not allowed to touch this"! P. S: I want to know why Oracle guys are obsessed with the final abstraction. I know they know more than I do, but in this special case of networkinterface, why is the final abstraction? Using a single comprehensive constructor makes the class immutable
Solution
You can use powermockito to simulate the 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 only be used in very rare and inevitable situations