用phpunit测试错误404

时间:2015-07-30 11:00:59

标签: php phpunit

我的测试的目的是检查一个函数返回错误404,或者更准确,函数创建调用服务器(我正在使用guzzle),我希望服务器返回错误404,但我不能找到任何有意义的@expectedException因为它是一个错误,但有谁知道如何用phpunit测试这个案例??? THX

如果它有帮助,这就是函数的样子(最后一次尝试):

public function testApi_deleteExecuted()
  {
     $path = '/adserver/src/public/api/rule/288';
     $client = new Client(['base_uri' => 'http://10.0.0.38']);
     $response = $client->get($path);
     $data = json_decode($response->getBody());
     $code = $response->getStatusCode();

     $this->assertEquals($code, 404);

  }

2 个答案:

答案 0 :(得分:5)

显然,guzzle有答案,http_errors

功能之前没有用,但它现在有效:

  public function testApiRule_deleteExecuted()
  {
     $path = '/adserver/src/public/api/rule/288';
     $client = new Client(['base_uri' => 'http://10.0.0.38']);
     $response = $client->get($path, ['http_errors' => false]);
     $err = $response->getStatusCode();

     $this->assertEquals($err, 404);
  }

答案 1 :(得分:1)

Laravel 中的解决方案:

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Symfony\Component\HttpFoundation\Response;
use Tests\TestCase;

class Page404Test extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function page_status_is_404()
    {
        $response = $this->get('yahoo/oops')
            ->assertSee('Error 404. No such page.');

        $response->assertStatus(Response::HTTP_NOT_FOUND); // 404.
    }
}