[英]Laravel REST API Testing in phpunit
我正在尝试通过 Z85AF727FD022D3A13E7972FD6ZA41 测试 Laravel REST API。 在测试 REST 调用时,我无法隔离 REST 调用测试。
在 Laravel 中,我了解了一些选项,例如使用特征DatabaseMigrations
、 DatabaseRefresh
、 DatabaseTransactions
。 但我不能使用这些,原因如下:
DatabaseMigrations
:应用程序没有正确的迁移。 即使它有,那些也将是非常低效的。
DatabaseRefresh
:同上。
DatabaseTransactions
。 我看到的问题是对 HTTP API 的调用是一个完全不同的过程。 这些不在同一个事务中。 因此,HTTP 调用看不到插入数据以设置测试用例的测试。 此外,如果通过 HTTP 插入数据,则其他测试将可以看到类似的调用。
如果不调用 HTTP,我就无法编写单元测试; 该应用程序不是以这种方式编写的。 整个代码在Routes
或Controller
中,否则不可测试。
我用 json function 测试我的端点(我相信也有 POST 和 GET 方法,但我需要传入数据和标题)
public function test_endpoint() {
$result = $this->json('POST', '/api', ['key' => 'data'], ['Header' => "Value"]);
}
我也有单元和功能测试,但我用它来测试 graphQL 端点。
所以在我的例子中, void
意味着我们的方法不返回任何东西。 postJson
意味着我们期望JSON
响应,或者我们可以只做$this->post()
你可以像这样拨打电话
public function test_create_order() : void
{
$response = $this->postJson('/make-order',[
'foo' => 'bar',
'baz' => 'bat'
]);
// To make sure it is returning 201 created status code, or other code e.g. (200 OK)
$response->assertStatus(201);
// To make sure it is in your desired structure
$response->assertJsonStructure([
'id',
'foo',
'baz',
]);
// Check if response contains exactly that value, what we inserted
$this->assertEquals('bar', $response->json('data.foo'));
// Check that in the database created that record,
// param 1 is table name, param 2 is criteria to find that record
// e.g. ['id' => 1]
$this->assertDatabaseHas('orders', [
'foo' => 'bar'
]);
// Also there is other method assertDatabaseMissing, that works like above
// just in reverse logic, it is checking that there is no record with that criteria
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.