我正在构建一个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');
}
}
然后在我的测试中,我使用我正在注入的方法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!
}
}
如何在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);
}
}
因此,我必须模拟Accept,以便查看我的wantsYaml方法是否按预期工作.