美文网首页
如何对Web服务的API进行Unit Test?

如何对Web服务的API进行Unit Test?

作者: PageThinker | 来源:发表于2019-02-23 17:51 被阅读17次

为什么要求对Web服务的API进行测试?请移步这里Java中几种Unit Test场景

假设:我们需要需要对前端提供一个API,这个API的功能是:通过结果关键字查询产品的描述信息;

目录:
1,建立API契约
2, API代码
3, 测试代码:测试参数,测试找到资源情况下的返回结果,测试未找到资源是的返回结果


建立API的契约:

建议使用Swagger 的yaml格式来定义,这里为了易读,使用纯中文描述.

    GET请求
    http://localhost:8888/api/products/{productId}

查询参数:

          countryCode: String

返回结果:

200: 找到了相关资源
           {
                     "name" : "ABC",
                     "countryCode" : "US",
                     "description" : "Super ABC"
           }

404:  未找到资源
            {
                   "message": "Not found."
            }

API代码

ProductResource

@RestController
@RequestMapping("/api/products")
public class ProductResource {
    
    @Autowired
    private ProductService productService;

    @GetMapping("/{productId}
    public Product query(@PathVariable("productId") String productId, 
                         @RequestParam("countryCode") String countryCode) thrown NotFoundException {
        productService.query(productId, countryCode);
    }
}

ProductService

@Service
public class ProductService {

    public ProductDTO query(String productId, String countryCode) throws NotFoundException {
        if ("ABC".equals(productId) && "US".equals(countryCode)) {
            return new ProductDTO("ABC", "US", "Super ABC");
        }
        throw new NotFoundException("Not found");
    }
}

ProductDTO

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ProductDTO {
    private String name;
    private String countryCode;
    private String description;
}

测试代码

测试参数:should_response_4XX_when_country_code_is_empty()
测试找到资源情况下的返回结果:should_response_expected_product_information_when_find_product_by_product_id_and_country_code()
测试未找到资源是的返回结果:should_response_404_when_product_not_found_by_produt_id_and_country_code()

@RunWith(SpringRunner.class)
@SpringBootTest(class=Application.class)
public class ProductResourceTest {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    protected MockMvc mockMvc;

    @Autowired
    private ProductResource productResource;

    @Autowired
    private ProductService productService;

    @Autowired
    private GlobalEntityExceptionHandler globalEntityExceptionHandler;

   @BeforeClass
   public static void setup() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(productResource)
                          .setControllerAdvice(globalEntityExceptionHandler)
                          .build();
   }
   

    @Test
    public void should_response_4XX_when_country_code_is_empty() {
        mockMvc.perform(
               get("/api/products/ABC")
                   .contentType(MediaType.APPLICATION_JSON))
           .andExpect(status().is4xxClientError());
    }


    @Test
    public void should_response_expected_product_information_when_find_product_by_product_id_and_country_code() {
        String expectedResult = OBJECT_MAPPER.writeValueAsString(ProductDTO.builder()
            .name("ABC")
            .countryCode("US");
            .description("Super ABC")
            .build());

        mockMvc.perform(
               get("/api/products/ABC")
                   .contentType(MediaType.APPLICATION_JSON)
                   .param("countryCode", "US"))
           .andExpect(status().isOk())
           .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
           .andExpect(content().String(expectedResult));
    }


    @Test
    public void should_response_404_when_product_not_found_by_produt_id_and_country_code() {
      String expectedResult = "{\"message\":\"\"}";

        mockMvc.perform(
               get("/api/products/AAA")
                   .contentType(MediaType.APPLICATION_JSON)
                   .param("countryCode", "GB"))
           .andExpect(status().isNotFound())
           .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
           .andExpect(content().String(expectedResult));
    }
}

相关文章

网友评论

      本文标题:如何对Web服务的API进行Unit Test?

      本文链接:https://www.haomeiwen.com/subject/ltupyqtx.html