【问题标题】:codeception - mocking api call datacodeception - 模拟 api 调用数据
【发布时间】:2014-05-29 23:57:18
【问题描述】:

我正在为一个前端应用程序构建和编写测试,该应用程序正在为其所有数据调用 API。我正在使用 Codeception 进行测试。到目前为止,功能测试和验收测试都在工作,但是我希望功能测试独立于 API,这样我就可以在不依赖 API 服务应用程序的情况下运行它们。

有没有办法模拟来自 API 调用的数据?或者这是单元测试的领域?

【问题讨论】:

  • 这可能取决于您用来进行这些 API 调用的 REST 库。否则,与框架和库无关的解决方案将是创建一个轻量级服务器进程来模拟 API 响应并在测试时使用该服务器而不是真正的 API 服务器。
  • 看看apiary.io 可以用来设计和模拟一个API

标签: laravel-4 codeception


【解决方案1】:

我使用 PHPUnit 进行 API 测试。我希望这会对你有所帮助。

我刚刚为此测试提供了一些示例输入数据,并验证它将按预期返回错误/成功代码 如果 test 没有得到预期的返回码,则会提示错误。

class ForgotPasswordTest extends \TestCase{

    /**
     * Test Forgot Password API With valid parameters
     * It will check forgot password functionality with success conditions
     */

    public function testForgotPasswordWithValidParameter()
    {
        $param=array("email"=>"shindesatishsss@gmail.com");
        $response = $this->call('POST', 'forgotPassword',$param);
        $data = json_decode($response->getContent(), true);
        if(!isset($data["code"]))
            $this->assertFalse(false);
        /** check response code
         *  Return 600 in case if API executed successfully
         */
        $this->assertEquals("600", $data["code"]);
    }

    /**
     * Test Forgot Password API With Invalid parameters
     * It will check whether you have applied user exist condition
     */

    public function testForgotPasswordWithInValidParameter()
    {
        $param=array("email"=>"test@test.com");
        $response = $this->call('POST', 'forgotPassword',$param);
        $data = json_decode($response->getContent(), true);
        if(!isset($data["code"]))
            $this->assertFalse(false);
        /** check response code
         *  Return 404 if user not found
         */
        $this->assertEquals("404", $data["code"]);
    }

    /**
     * Test Forgot Password API With Invalid parameters
     * It will check input validations are working fine in the API
     */

    public function testForgotPasswordWithInValidEmail()
    {
        $param=array("email"=>"satish");
        $response = $this->call('POST', 'forgotPassword',$param);
        $data = json_decode($response->getContent(), true);
        if(!isset($data["code"]))
            $this->assertFalse(false);
        /** check response code
         *  Return 400 error code if there are some input validation error
         */
        $this->assertEquals("400", $data["code"]);
    }

} 

您也可以设置一些其他的测试用例,因为只需要在这个类中创建具有不同测试用例的新函数。

【讨论】:

    【解决方案2】:

    查看 Mocky (http://www.mocky.io) 以获取您可以自定义的实时模拟 HTTP 响应。此外,它是创建令人难以置信的存根 JSON 对象的绝佳工具,请查看 JSON-Generator (http://www.json-generator.com/)。

    【讨论】:

      猜你喜欢
      • 2016-04-15
      • 2017-06-25
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      相关资源
      最近更新 更多