JUnit 的模拟 WebClient

Mock WebClient for JUnit

提问人:unknown1101 提问时间:11/16/2023 最后编辑:Lesiakunknown1101 更新时间:11/17/2023 访问量:63

问:

如何在 JUnit 测试用例中模拟 Web 客户端,以便可以测试以下使用 Web 客户端的方法?

public class Service {
    
    @Autowired
    private WebClient webClient;

    public Flux<String> callExternal(Request request) throws Exception {

    return webClient.post()
        .uri(externalAPIUrl)
        .accept(MediaType.APPLICATION_JSON)
        .body(Mono.just(util.convertRequest(request)), ExpectedRequest.class)
        .headers(headers -> headers.add("token",util.getToken()))
        .retrieve().bodyToFlux(String.class);
    }
}

我试过什么:

 public class ServiceTest { 
         
    @Mock
    private WebClient webClient; 
   
    @InjectMocks
    Service service;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }      

    @Test
    public void testCallExternal() throws Exception {

       MockitoAnnotations.openMocks(this);

       Request request = Request.builder().id("1").build();
       Flux<String> result = Flux.just("test");   
      
       WebClient.RequestBodyUriSpec requestBodyUriSpec = mock(WebClient.RequestBodyUriSpec.class);
       WebClient.RequestBodySpec requestBodySpec = mock(WebClient.RequestBodySpec.class);
       WebClient.RequestHeadersSpec requestHeadersSpec = mock(WebClient.RequestHeadersSpec.class);
       WebClient.ResponseSpec responseSpec = mock(WebClient.ResponseSpec.class);  
        
       String externalURL = "external url";

       when(webClient.post()).thenReturn(requestBodyUriSpec);
       when(requestBodyUriSpec.uri(anyString())).thenReturn(requestBodySpec);
       when(requestBodySpec.contentType(any())).thenReturn(requestBodySpec);
       when(requestHeadersSpec.retrieve()).thenReturn(responseSpec);
       when(responseSpec.onStatus(any(), any())).thenReturn(responseSpec);
       when(responseSpec.bodyToFlux(String.class)).thenReturn(result); 
       
       Flux<String> serviceResponse = Service.callExternal(request);

       assertThat(serviceResponse != null);
    }
}

我在服务类中 callExternal() 的 webClient.post() 的第一行从 Web 客户端收到空指针异常。

JUnit Mockito WebClient

评论

0赞 Reg 11/16/2023
你能添加你尝试过的东西吗?还是您使用过的资源?
0赞 unknown1101 11/16/2023
现在肯定更新了,谢谢。
0赞 Lesiak 11/17/2023
你怎么传给(在我看来,你不是)。如何在您的服务中初始化?webClientMockServicewebClient
0赞 unknown1101 11/17/2023
我已经更新了帖子,希望它更清楚
1赞 Lesiak 11/17/2023
你为什么要启动两次模拟?(initMocks 和 openMocks)

答: 暂无答案