Laravel:是否有可能直接测试函数的json响应输出而不实际通过URI?

时间:2018-04-28 17:53:19

标签: laravel testing phpunit

the docs,我可以使用以下内容测试从我的应用程序返回的一些json:

$response = $this->json('POST', '/user', ['name' => 'Sally']);

$response
    ->assertStatus(201)
    ->assertJson([
        'created' => true,
    ]);

但是,是否可以绕过实际使用$this->json(*method*, *uri*, *data*);调用URI,而是测试返回json的控制器函数的直接输出?例如,我想做这样的事情:

// My controller:

function getPageData(){
  $data = array('array', 'of', 'data');
  return response()->json($data);
}

// My Test Class:

$controller = new Primary();
$response = $controller->getPageData();

$response->assertJson([
    'array', 'of', 'data'
]);

这可能吗?

1 个答案:

答案 0 :(得分:1)

你可以为一些基本方法做到这一点,但它可能会导致副作用:

app(SomeController::class)->someControllerMethod();

基本上,app()将解析构造函数的依赖关系,但它不会解决方法依赖关系。因此,如果您键入类似method(Request $request)的内容,则会引发错误。

我非常确定处理request()会导致无意识的影响,因为没有真正的请求。

修改

然后,您可以创建一个TestResponse对象,以获取所有断言:

$res = app(SomeController::class)->someControllerMethod();
$testRes = new Illuminate\Foundation\Testing\TestResponse($res);
$testRes->assertJson(...); // Will be available