Spring Cloud gateway使用的是reactive,使用WebTestClient模拟发送请求。

待测试的方法如下,方法中会访问其它的服务,在单元测试时,我们要把这个语法mock掉。

public class EmployeeService {
    private WebClient.Builder webClient;
    public Mono<Employee> getEmployeeById(Integer employeeId) {
        return webClient
                .get()
                .uri("http://auth_user/v2/role/resources")
                .retrieve()
                .bodyToMono(Employee.class);
    }
}
@SpringBootTest(webEnvironment = RANDOM_PORT)
@ExtendWith(MockitoExtension.class)
public class GatewayTests {

    protected static WebTestClient webClient;
    @MockBean
    private WebClient webClientMock;
    @MockBean
    private WebClient.RequestHeadersSpec requestHeadersMock;
    @MockBean
    private WebClient.RequestHeadersUriSpec requestHeadersUriMock;
    @MockBean
    private WebClient.ResponseSpec responseMock;
	@LocalServerPort
    protected int port = 0;
    
    @BeforeEach
    public void setup()
    {
        String baseUri = "http://localhost:"+ port;
        webClient = WebTestClient.bindToServer()
                .baseUrl(baseUri)
                .responseTimeout(Duration.ofSeconds(12))
                .build();
    }

    /**
     * 测试
     */
    @Test
    public void test()  {
        GotRoleResourceDTO dto = new GotRoleResourceDTO();
        dto.setMethod("post");
        dto.setRoleId("ROLE-test");
        dto.setUrl("/auth_user/v2/test503");
        List<GotRoleResourceDTO> list = new ArrayList<>();
        list.add(dto);
        when(webClientBuilderMock.build()).thenReturn(webClientMock);

        when(webClientMock.get())
                .thenReturn(requestHeadersUriMock);
        when(requestHeadersUriMock.uri("http://auth_user/v2/role/resources")).thenReturn(requestHeadersMock);
        when(requestHeadersMock.retrieve()).thenReturn(responseMock);
        when(responseMock.bodyToFlux(GotRoleResourceDTO.class)).thenReturn(Flux.just(dto));


        webTestClient.get().uri("/auth_user/v2/test503")
                .header("Authorization","Bearer "+TOKEN)
                .exchange()
                .expectStatus().isEqualTo(503)
                .expectBody(String.class).consumeWith(result ->{
            String body = result.getResponseBody();
            log.debug("body:{}",body);
        });

    }

}

官方例子

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐