How to mock the discoveryClient?

Tags: , ,



I’m working with Eureka and I have a Method that uses the DiscoveryClient to obtain the instances of a service and the call this service and retrieve some information like this:

    List<ServiceInstance> instances = discoveryClient.getInstances(CSC_APP_NAME);
    ServiceInstance serviceInstance = instances.get(0);
    String baseUrl = serviceInstance.getUri().toString();
    baseUrl = baseUrl + usrEmail + "/services";
    ResponseEntity<Service> response = restTemplate.getForEntity(baseUrl, Service.class);

It works, but now I want to make a JUnit test for the method and as I’m not going to have the Eureka working in the JUnit test environment, I think I should mock the discoveryClient, but how should I make this mock? I’m using mockito in the project.

Answer

It’s correct to mock the discoveryClient in the unit test. Using Junit 5:

public class MyServiceTest {
    @InjectMocks
    private MyService myService;

    @Mock
    private DiscoveryClient discoveryClient;

    @Mock
    private RestTemplate restTemplate;

    @BeforeEach
    public void initTest() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void myTest() {
        ServiceInstance si = mock(ServiceInstance.class);
        when(si.getUri()).thenReturn(URI.create("myUri"));
        when(discoveryClient.getInstances(anyString()))
            .thenReturn(List.of(si));

        myService.myMethod();
    }
}

I also mocked the restTemplate, but that is up to you. MyService.myMethod() implementation:

public void myMethod() {
    List<ServiceInstance> instances =discoveryClient.getInstances("CSC_APP_NAME");
    ServiceInstance serviceInstance = instances.get(0);
    String baseUrl = serviceInstance.getUri().toString();
    baseUrl = baseUrl + "userEmail" + "/services";
    ResponseEntity<Service> response = restTemplate.getForEntity(baseUrl, Service.class);
}


Source: stackoverflow