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?
CodePudding user response:
Server serverMock = mock(Server.class);
does nothing. It will not mock the Server instance created within your getTotalModules
.
You could add createServer
method in ModuleSpectator
which you could mock then as well, but all you do then is just test if your mocking logic is correct.
Generally, if this code is complete and not a simplified version of what you're doing then it's probably not worthwhile writing a test for this.
CodePudding user response:
You need to inject your mock on the real object
Example:
Server serverMock = mock(Server.class);
ServerState serverState =new ServerState();
serverState.setTotalModules(50);
when(serverMock.getServerState(server_id)).thenReturn(serverState);
ModuleSpectator moduleSpectator = new ModuleSpectator(serverMock);
assertEquals(50, moduleSpectator.getTotalModules(server_id));