简体   繁体   English

使用PHPUnit测试REST API

[英]Testing REST APIs using PHPUnit

I am building a set of RESTful APIs and am now required to write unit tests for them. 我正在构建一组RESTful API,现在需要为它们编写单元测试。 I am not sure what the unit tests should actually test. 我不确定单元测试应该实际测试什么。

Should unit tests check whether the response being received from the server is correct for various inputs? 单元测试是否应检查从服务器接收的响应是否适用于各种输入? If so, is it a good practice to have a set of correct response formats pre-defined and check the responses against them? 如果是这样,预先定义一组正确的响应格式并检查针对它们的响应是否是一种好习惯?

UPDATE UPDATE

I am calling these services through CURL and I can definitely check status code. 我通过CURL调用这些服务,我绝对可以检查状态代码。 The response may vary for different inputs, so should I check for all possible responses? 对于不同的输入,响应可能会有所不同,因此我应该检查所有可能的响应吗?

How is unit testing usually done for RESTful APIs using PHPUnit in general? 通常如何使用PHPUnit对RESTful API进行单元测试?

If your API's data layer is sufficiently abstracted, so that you can receive consistent and predictable output for a given input, your test cases should definitely include some common output expectations for some finite list of inputs They should also test for any error cases you can drum up. 如果您的API的数据层被充分抽象化,以便您可以为给定的输入接收一致且可预测的输出,那么您的测试用例肯定应该包含一些有限的输入列表的一些常见输出预期。他们还应测试您可以鼓励的任何错误情况起来。

If your API can't run against a data layer that's in a predictable state (for example, if it's connected to live data, or to data that's shared among developers), you're going to end up spending a lot of time fixing your tests to correctly model the new state of the data. 如果您的API无法针对处于可预测状态的数据层(例如,如果它连接到实时数据或开发人员之间共享的数据),那么您最终将花费大量时间来修复测试以正确建模数据的新状态。 That makes unit testing less valuable, since you might not run them as often, and since you've never sure whether a test failure is due to a change in the data or a change in the program logic. 这使得单元测试的价值降低,因为您可能不会经常运行它们,并且因为您无法确定测试失败是由于数据的更改还是程序逻辑的更改。 Whether that outweighs the risk of not having unit tests or not will depend on your individual situation (how often do the tests break, how critical is the service, &ct). 这是否超过未进行单元测试的风险将取决于您的个人情况(测试中断的次数,服务的重要程度,以及ct)。

As far as how to use PHPUnit to run test cases, I can't answer that specifically, but I imagine that you'd do as @basiljames noted; 至于如何使用PHPUnit来运行测试用例,我无法回答具体问题,但我想你会像@basiljames所说的那样做; execute a call against a given endpoint and verify that the response received correctly matches your expectations. 对给定端点执行调用,并验证收到的响应是否符合您的期望。 Not that different from any other unit test, except for the fact that they may run a little more slowly. 与任何其他单元测试没有什么不同,除了它们可能运行得慢一点的事实。

You can use JUnit for your test cases. 您可以将JUnit用于测试用例。 You will have to check for HTTP Status Code and afterwards, the content on the reponse for any particular attribute or value. 您必须检查HTTP Status Code ,然后检查任何特定属性或值的响应内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM