如何在Laravel 5包中的测试中模拟Accept标头?

Dug*_*ugi 18 php testing phpunit package laravel-5

我正在构建一个Laravel包,它Illuminate\Http\Request通过注入一个新方法.我正在注入的方法已经完成,预计可以很好地工作,但我也想在发布它之前测试它.

我的测试要求我更改请求的Accept标题,以便我查看测试是否通过.所以我已经完成以下操作来模拟请求:

// package/tests/TestCase.php

namespace Vendor\Package;

use Illuminate\Http\Request;
use Orchestra\Testbench\TestCase as Orchestra;

abstract class TestCase extends Orchestra
{
    /**
     * Holds the request
     * @var Illuminate\Http\Request
     */
    protected $request;

    /**
     * Setup the test
     */
    public function setUp()
    {
        parent::setUp();

        $this->request = Request::capture();

        $this->request->headers->set('Accept', 'application/x-yaml');
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的测试中,我使用我正在注入的方法Request,$this->request->wantsYaml()并且它始终返回false,因为Accept标头未设置为application/x-yaml.

class RequestTest extends TestCase
{
    /** @test */
    public function it_should_return_a_bool_if_page_wants_yaml_or_not()
    {
        dump($this->request->wantsYaml()); // Return false

        $this->assertTrue($this->request->wantsYaml()); // It fails!
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在Laravel包开发中继续模拟测试中的头文件?


编辑

这是我的YamlRequest班级

use Illuminate\Http\Request;
use Illuminate\Support\Str;

class YamlRequest extends Request
{
    /**
     * Acceptable content type for YAML.
     * @var array
     */
    protected $contentTypeData = ['/x-yaml', '+x-yaml'];

    /**
     * Determine if the current request is asking for YAML in return.
     *
     * @return bool
     */
    public function wantsYaml()
    {
        $acceptable = $this->getAcceptableContentTypes();

        // If I dd($acceptable), it comes out as empty during tests!

        return isset($acceptable[0]) && Str::contains($acceptable[0], $this->contentTypeData);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,我必须模拟Accept,以便查看我的wantsYaml方法是否按预期工作.

Mar*_*łek -1

好吧,说实话,我不知道你如何YamlRequest在代码中使用它,但我认为这里有两个问题:

1)在你的测试中你创建了Illuminate\Http\Request对象而不是YamlRequest对象 - 这是正确的吗?对我来说似乎不是,但也许应该是这样的

2)第二件事是方法的代码。查看您的方法实现,您设置了无效标头,因为getAcceptableContentTypes()方法获取Accept标头而不是Content-Type

如果我将测试代码更改为如下所示:

$request = new \App\Http\Requests\YamlRequest();
$request->headers->set('Accept', 'application/x-yaml');
$this->assertTrue($request->wantsYaml()); 
Run Code Online (Sandbox Code Playgroud)

它过去了。但我必须使用Acceptheader 而不是Content-Type. 我认为这就是错误。