如何模拟 discoveryClient?

How to mock the discoveryClient?

我正在使用 Eureka,我有一个使用 DiscoveryClient 获取服务实例并调用此服务并检索一些信息的方法,如下所示:

    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);

它有效,但现在我想对该方法进行 JUnit 测试,因为我不打算让 Eureka 在 JUnit 测试环境中工作,我想我应该模拟 discoveryClient,但我应该怎么做做这个模拟?我在项目中使用 mockito。

在单元测试中mock discoveryClient是正确的。使用 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();
    }
}

我还嘲笑了restTemplate,但这取决于你。 MyService.myMethod() 实施:

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);
}