Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring boot 如何为网关云过滤器编写junit5测试,以及如何获得此代码的完整代码覆盖率_Spring Boot_Unit Testing_Spring Cloud_Junit5_Spring Cloud Gateway - Fatal编程技术网

Spring boot 如何为网关云过滤器编写junit5测试,以及如何获得此代码的完整代码覆盖率

Spring boot 如何为网关云过滤器编写junit5测试,以及如何获得此代码的完整代码覆盖率,spring-boot,unit-testing,spring-cloud,junit5,spring-cloud-gateway,Spring Boot,Unit Testing,Spring Cloud,Junit5,Spring Cloud Gateway,我想为我的网关云过滤器编写junit测试,但问题是我不熟悉单元测试。请帮帮我。这里有一个私有的授权方法 [如果有人不知道如何编写SpringGatewayCloudFilter,请查看我的GatewayFilter方法和逻辑] @Component @Slf4j public class AuthorizationFilter extends AbstractGatewayFilterFactory<AuthorizationFilter.Config> { @Value(

我想为我的网关云过滤器编写junit测试,但问题是我不熟悉单元测试。请帮帮我。这里有一个私有的授权方法

[如果有人不知道如何编写SpringGatewayCloudFilter,请查看我的GatewayFilter方法和逻辑]

@Component
@Slf4j
public class AuthorizationFilter extends AbstractGatewayFilterFactory<AuthorizationFilter.Config> {

    @Value("${rest.auth.service.url}")
    private String authServiceUrl;

    @Autowired
    RestTemplate restTemplate;

    public AuthorizationFilter() {
        super(Config.class);
    }

    private Mono<Void> onError(ServerWebExchange exchange, String err, HttpStatus httpStatus) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(httpStatus);

        return response.setComplete();
    }
    //Here is my authorization details 
    private UserRoleDetailsDTO getAuthorizationDetails(String authorizationHeader) {
        try {
            log.error("Checking authorization");
            HttpEntity<?> entity = new HttpEntity(null, new HttpHeaders() {{
                add("Authorization", authorizationHeader);
                add("Accept", "application/json");
            }});

            ResponseEntity<Map> responseMap = restTemplate.exchange(authServiceUrl.concat("/v1/profile"), HttpMethod.GET, entity, Map.class);
            System.out.println(responseMap);
            if (responseMap.getBody() == null)
                log.warn("Received null body in response. Request will end now");
            Map data = (Map) responseMap.getBody().get("data");
            boolean isAuthorized = data.get("authorized") == null || (boolean) data.get("authorized");
            UserRoleDetailsDTO userRoleDetailsDTO = UserRoleDetailsDTO.builder().userId(String.valueOf(data.get("userId"))).
                    roles((List<RoleDTO>) data.get("roles")).isAuthorized(isAuthorized).build();
            return userRoleDetailsDTO;
        } catch (RestClientException e) {
            String errorResponse = null;
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException exception = (HttpClientErrorException) e;
                errorResponse = exception.getResponseBodyAsString();
            } else errorResponse = e.getMessage();
            log.error("error with http connect with error response : {} : {}", errorResponse, e);
            return null;
        } catch (Exception e) {
            log.error("error with http connect : {}", e);
            return null;
        }
    }
    // Here is my Gateway filter
    @Override
    public GatewayFilter apply(Config config) {

        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();

            String requestId;
            if (request.getHeaders().containsKey("Request-Id")) {
                requestId = request.getHeaders().get("Request-Id").get(0);
            } else {
                requestId = UUID.randomUUID().toString();
                log.debug("Request Id not passed. {} is genertaing requestId {}", AuthorizationFilter.class.getSimpleName(), requestId);
            }
            MDC.put("requestId", requestId);
            request.mutate().header("Request-Id", requestId);

            if (!request.getHeaders().containsKey("Authorization")) {
                log.error("No authorization header");
                return onError(exchange, "No Authorization header", HttpStatus.UNAUTHORIZED);
            }

            String authorizationHeader = request.getHeaders().get("Authorization").get(0);

            UserRoleDetailsDTO userRoleDetailsDTO = getAuthorizationDetails(authorizationHeader);
            if (userRoleDetailsDTO == null || !userRoleDetailsDTO.isAuthorized()) {
                log.error("Invalid authorization header");
                return onError(exchange, "Invalid Authorization header", HttpStatus.UNAUTHORIZED);
            }
            String userDetailsStr = "";
            try {
                userDetailsStr = new ObjectMapper().writeValueAsString(userRoleDetailsDTO);
                System.out.println("value 1 :"+userDetailsStr);
            } catch (JsonProcessingException e) {
                log.error("Exception writing user details to string. ", e);
            }
            if (StringUtils.isEmpty(userDetailsStr))
                log.warn("Empty User Details string being passed!!");
            request.mutate().header(ApplicationConstants.USER_DETAILS_HEADER, userDetailsStr);
            System.out.println("value 2 :"+request.mutate().header(ApplicationConstants.USER_DETAILS_HEADER, userDetailsStr));
            return chain.filter(exchange.mutate().request(request).build());
        };

    }

    @Override
    public Config newConfig() {
        return new Config();
    }

    public static class Config {
        // Put the configuration properties
    }

}
这是我的junit测试,当我在代码覆盖率下运行时,我没有得到完全的代码覆盖率,请帮助我

 public YourClassTest{   

    @Test
    void apply() throws Exception {
        AuthorizationFilter authorizationFilter  = new AuthorizationFilter();
        AuthorizationFilter.Config config = new YourClass.Config();
        GatewayFilter filter =authorizationFilter.apply(config);
        String st ;
        st = new  ObjectMapper().writeValueAsString(userRoleDetailsDTO);
             MockServerHttpRequest expected  = MockServerHttpRequest.get("/v1/profile").
               header("Authorization", "Bearer sdfsf",st, TestConstants.USER_DETAILS_HEADER).build();
        MockServerWebExchange exchange = MockServerWebExchange.from(expected);
        filter.filter(exchange,FilterChain);
        String requestid;
        ServerHttpRequest actual =  exchange.getRequest();
        assertEquals(expected,actual);
    }
 }

我等了两天,有人会回答我的问题,但没有人回答我的问题,但最后我解决了。我用的是junit5

这是我的正确答案

@SpringBootTest(properties = { "spring.profiles.active=test" })
class AuthorizationFilterTest {

    @Mock
    GatewayFilterChain filterChain;
    @MockBean()
    RestTemplate restTemplate;
    @Autowired
    AuthorizationFilter authorizationFilter = new AuthorizationFilter();
    
    @BeforeAll
    public static void init() {
    userRoleDetailsDTO = new UserRoleDetailsDTO();
    RoleDTO roleDTO = new RoleDTO();
    roleDTO.setName("ADMIN_ROLE");
    roleDTO.setWeight(1);
    userRoleDetailsDTO.setUserId("user::2f840056-e7aa-84m- 68e1-1e2ef697c78b");
    userRoleDetailsDTO.setRoles(Stream.of(roleDTO).collect(Collectors.toList()));

}


    @Test
    void apply()
    {
     AuthorizationFilter.Config config = new AuthorizationFilter.Config();
    Map<String, Object> profile = objectMapper.readValue(TestConstantsTest.ADMIN_PROFILE_RESPONSE, Map.class);
    ResponseEntity<Map> profileMap = ResponseEntity.ok(profile);
    Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.any(HttpMethod.class),
            Mockito.any(HttpEntity.class), Mockito.eq(Map.class))).thenReturn(profileMap);
    GatewayFilter filter = authorizationFilter.apply(config);
    MockServerHttpRequest expected = MockServerHttpRequest.post("/v1/profile")
            .header("Authorization", TestConstantsTest.ADMIN_INITIALISE_REQUEST_AUTH_HEADER).build();
    MockServerWebExchange exchange = MockServerWebExchange.from(expected);
    filter.filter(exchange, GatewayfilterChain);
    ServerHttpRequest actual = exchange.getRequest();
    assertEquals(expected, actual);
   
    }

您应该更新标题,说“帮助我在单元测试中获得完整的代码覆盖”。正如标题所示,您需要帮助编写测试。由于if语句和异常处理,您可能需要使用不同的模拟请求进行多个测试以获得完整覆盖。感谢Spencergib提供的建议
 public YourClassTest{   

    @Test
    void apply() throws Exception {
        AuthorizationFilter authorizationFilter  = new AuthorizationFilter();
        AuthorizationFilter.Config config = new YourClass.Config();
        GatewayFilter filter =authorizationFilter.apply(config);
        String st ;
        st = new  ObjectMapper().writeValueAsString(userRoleDetailsDTO);
             MockServerHttpRequest expected  = MockServerHttpRequest.get("/v1/profile").
               header("Authorization", "Bearer sdfsf",st, TestConstants.USER_DETAILS_HEADER).build();
        MockServerWebExchange exchange = MockServerWebExchange.from(expected);
        filter.filter(exchange,FilterChain);
        String requestid;
        ServerHttpRequest actual =  exchange.getRequest();
        assertEquals(expected,actual);
    }
 }
@SpringBootTest(properties = { "spring.profiles.active=test" })
class AuthorizationFilterTest {

    @Mock
    GatewayFilterChain filterChain;
    @MockBean()
    RestTemplate restTemplate;
    @Autowired
    AuthorizationFilter authorizationFilter = new AuthorizationFilter();
    
    @BeforeAll
    public static void init() {
    userRoleDetailsDTO = new UserRoleDetailsDTO();
    RoleDTO roleDTO = new RoleDTO();
    roleDTO.setName("ADMIN_ROLE");
    roleDTO.setWeight(1);
    userRoleDetailsDTO.setUserId("user::2f840056-e7aa-84m- 68e1-1e2ef697c78b");
    userRoleDetailsDTO.setRoles(Stream.of(roleDTO).collect(Collectors.toList()));

}


    @Test
    void apply()
    {
     AuthorizationFilter.Config config = new AuthorizationFilter.Config();
    Map<String, Object> profile = objectMapper.readValue(TestConstantsTest.ADMIN_PROFILE_RESPONSE, Map.class);
    ResponseEntity<Map> profileMap = ResponseEntity.ok(profile);
    Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.any(HttpMethod.class),
            Mockito.any(HttpEntity.class), Mockito.eq(Map.class))).thenReturn(profileMap);
    GatewayFilter filter = authorizationFilter.apply(config);
    MockServerHttpRequest expected = MockServerHttpRequest.post("/v1/profile")
            .header("Authorization", TestConstantsTest.ADMIN_INITIALISE_REQUEST_AUTH_HEADER).build();
    MockServerWebExchange exchange = MockServerWebExchange.from(expected);
    filter.filter(exchange, GatewayfilterChain);
    ServerHttpRequest actual = exchange.getRequest();
    assertEquals(expected, actual);
   
    }
    Class TestConstantTest
    {
         public static final String ADMIN_PROFILE_RESPONSE = "{\n" +
                "   \"code\":\"200\",\n" +
                "   \"data\":{\n" +
                "      \"myroles\":[\n" +
                "         {\n" +
                "            \"name\":\"ADMIN_ROLE\",\n" +
                "            \"weight\":\"1\"\n" +
                "         }\n" +
                "      ],\n" +
                "      \"userId=User\":\"manually-inserted-usser-user-id-normallt-uuid\"\n" +
                "   },\n" +
                "   \"message\":\"Success\",\n" +
                "   \"status\":1\n" +
                " }";
    
        public static final String ADMIN_INITIALISE_REQUEST_AUTH_HEADER ="Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX" +
                "VCJ9.eyJhdWQiOlsicmVzb3VyY2Utc2VydmVghingbshtYXBpIl0sImV4cCI6MTU5NTI0NDU2MywidXNlcl9uYW1lIj" +
                "oiYzNlMjk0MGEtYzM3ZS0xMWVhLTg3ZDAtMDI0MmFjMTMwMDAzIiwianRpIjoiZTNkZDA1MTEtNDM0NC00MjhiLTk2Z" +
                "WQtYjUzNzU3Y2uytrewqasdY2xpZW50X2lkIjoic3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsa" +
                "WVudCIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdfQ.HvbThWCTqs2y9dP87kE31PmPA-EFk3J6HDFyAiEQlsM";
}