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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With