我正在执行以下操作来测试对Laravel的POST调用。我期待根据我的路线,对问题的帖子将作为存储操作方法被分派。这在浏览器中有效。
我的测试:
public function setUp()
{
parent::setUp();
Session::start();
}
public function testStoreAction()
{
$response = $this->call('POST', 'questions', array(
'_token' => csrf_token(),
));
$this->assertRedirectedTo('questions');
}
但是,我告诉我重定向不匹配。此外,我还可以看到它根本不会转到store操作方法。我想知道它将转到哪个操作方法,以及为什么它不会转到存储方法(如果我查看route:list,我可以看到有一个POST问题/路由应该转到questions.store;这在浏览器中也有效,但在我的测试中不起作用)。另外,我是否正确地编写了此资源的调用?我在这里添加了令牌,因为它抛出了一个应该抛出的异常,在某些测试中,我会让令牌检查通过。
发布于 2015-11-02 09:33:29
你可以试试这个:
public function testStoreAction()
{
Session::start();
$response = $this->call('POST', 'questions', array(
'_token' => csrf_token(),
));
$this->assertEquals(302, $response->getStatusCode());
$this->assertRedirectedTo('questions');
}
发布于 2015-03-05 20:47:02
测试路由的最推荐方法是检查200
响应。当你有多个测试时,这是非常有用的,比如你一次检查所有的post
路由。
为此,只需使用:
public function testStoreAction()
{
$response = $this->call('POST', 'questions', array(
'_token' => csrf_token(),
));
$this->assertEquals(200, $response->getStatusCode());
}
发布于 2019-12-12 21:54:03
我使用
$response->assertSessionHasErrors(['key'=>'error-message']);
为了断言验证工作。但是要使用它,您必须从要发送post请求的页面开始。如下所示:
$user = User::where('name','Ahmad')->first(); //you can use factory. I never use factory while testing because it is slow. I only use factory to feed my database and migrate to make all my test faster.
$this->actingAs($user)->get('/user/create'); //This part is missing from most who get errors "key errors is missing"
$response = $this->post('/user/store', [
'_token' => csrf_token()
]);
//If you use custom error message, you can add as array value as below.
$response->assertSessionHasErrors(['name' => 'Name is required. Cannot be empty']);
$response->assertSessionHasErrors(['email' => 'Email is required. Make sure key in correct email']);
然后如果你想测试错误是否也被正确地显示了回来。再次运行以上测试,并进行一些更改,如下所示:
$this->actingAs($user)->get('/user/create');
$response = $this->followingRedirects()->post('/user/store', [
'_token' => csrf_token()
]); //Add followingRedirects()
$response->assertSeeText('Name is required. Cannot be empty');
$response->assertSeeText('Email is required. Make sure key in correct email');
我的猜测是,如果你不从页面开始显示错误,(你放置表单的创建/更新页面),在这个过程中的会话链将会遗漏一些重要的键。
https://stackoverflow.com/questions/28790348
复制相似问题