Middle
How to write a unit test for a method that calls an external system so that no real call occurs?
sobes.tech AI
Answer from AI
To write a unit test for a method that interacts with an external system and to avoid actual calls, mocking is used. This means that instead of calling the real external system, a mock is created that returns predefined data.
In Java, libraries like Mockito or EasyMock are often used for this purpose. Here's an example with Mockito:
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
class ExternalService {
public String fetchData() {
// Real call to external system
return "real data";
}
}
class MyService {
private ExternalService externalService;
public MyService(ExternalService externalService) {
this.externalService = externalService;
}
public String process() {
String data = externalService.fetchData();
return "Processed " + data;
}
}
public class MyServiceTest {
@Test
void testProcess() {
ExternalService mockService = mock(ExternalService.class);
when(mockService.fetchData()).thenReturn("mocked data");
MyService myService = new MyService(mockService);
String result = myService.process();
assert result.equals("Processed mocked data");
}
}
This approach allows isolating the code under test from external dependencies and testing the logic without network delays and external system instability.