I'm trying write unit test on a method which has internal server connection (let's say socket connection). My test case is failing and I think the issue is with the way I mock the object. I'm new to unit tests so I have no idea what to next.
This is the method I'm trying to test.
class ModuleSpectator {
public long getTotalModules(String server_id){
Server server = new Server(server_ip); // this connects to a 3rd party server.
ServerState serverState =server.getServerState(server_id); // resposnse from the server
return = (long) serverState.getTotalModules();
}
}
This is the unit test.
@Test
public void testGetTotalModules(){
String server_id="ser_01";
ModuleSpectator moduleSpectator = mock(ModuleSpectator.class);
Server serverMock = mock(Server.class);
ServerState serverState =new ServerState();
serverState.setTotalModules(50);
when(serverMock.getServerState(server_id)).thenReturn(serverState);
assertEquals(50, moduleSpectator.getTotalModules(server_id));
}
when moduleSpectator.getTotalModules(server_id) in assertEquals() is executing, it actually trying to connect the 3rd party server. How do I stop this behavior and succefully set and mock the response?