How to validate API in tests with Swagger?

南笙酒味 提交于 2020-01-28 09:16:03

问题


I'm trying to figure out the best way to have my API documentation be the source of truth and use it to validate the actual Java REST code ideally through integration testing or something of that sort. We're using the contract first or consumer contract type of approach, so we don't want the documentation to be generated from annotated code necessarily and updating every time a developer makes a change.

One thought has been to use Swagger, but I'm not sure how best to make it be used for validating the API. Ideally, it'd be good to have the validation occur in the build or integration testing process to see if the real response (and request if possible) match what's expected. I know there are a lot of uses and tools for Swagger and just trying to wrap my head around it. Or if there is a better alternative to work with Java code.


回答1:


Recently, we (swagger-codegen community) start adding automatic test case generation to API clients (C#, PHP, Ruby). We've not added that to Java yet. Here are some example test cases generated by Swagger-Codegen for C#:

https://github.com/swagger-api/swagger-codegen/tree/master/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test

It's still very preliminary and we would like to hear feedback from you to see if that's what you're looking for.




回答2:


I think you should try swagger-request-validator: https://bitbucket.org/atlassian/swagger-request-validator

Here are some examples how to use it: https://bitbucket.org/atlassian/swagger-request-validator/src/master/swagger-request-validator-examples/

Another alternative is assertj-swagger: https://github.com/RobWin/assertj-swagger




回答3:


You may want to look at Spring Cloud Contract. It offers you a DSL, where you can describe the scenarios (more or less what is the response I get for a given request) and it seems to fit well to what you described as a requirement...




回答4:


If you're using the Spring Framework, I'd highly recommend checking out Spring RestDocs which allow you to generate



来源:https://stackoverflow.com/questions/34817307/how-to-validate-api-in-tests-with-swagger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!