如何在Laravel 5软件包中的测试中模拟接受标头?
我目前正在构建一个Laravel包,该包通过Macros注入新方法。我正在注入的方法已经完成,预计可以很好地工作,但我也想在发布之前对其进行测试。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');
}
}
然后在我的测试中,我使用我正在注入的方法,它总是返回false,因为标头未设置为。Request
$this->request->wantsYaml()
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!
}
}
如何在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);
}
}
因此,我必须模拟“接受”,才能查看我的方法是否按预期工作。wantsYaml