本文介绍了phpunit中的Laravel REST API测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过phpunit测试Laravel REST API.在测试REST调用时,我无法隔离REST调用测试.

I am trying to test a Laravel REST API, through phpunit. While testing REST calls, I am unable to isolate REST calls test.

在Laravel中,我了解一些选项,例如使用特征 DatabaseMigrations DatabaseRefresh DatabaseTransactions .但由于以下原因,我无法使用它们:

In Laravel, I understand a few options like using traits DatabaseMigrations, DatabaseRefresh, DatabaseTransactions. But I can't use these for the following reasons:

  • DatabaseMigrations :该应用没有正确的迁移.即使有,它们的效率也很低.

  • DatabaseMigrations: The app does not have proper migrations. Even if it had, those would be quite in-efficient.

DatabaseRefresh :与上面相同.

DatabaseTransactions .我看到的问题是对HTTP API的调用是一个完全不同的过程.这些不在同一笔交易中.因此,HTTP调用无法看到插入数据以设置测试用例的测试.另外,如果数据是通过HTTP调用插入的,则其他测试也可以看到.

DatabaseTransactions. The problem I see is that call to HTTP API is a completely different process. These are not within the same transaction. So a test that inserts data to setup the test case is not seen by HTTP call. Also, if data is inserted by HTTP calls like will be visible to other tests.

我不编写HTTP就无法编写单元测试;该应用程序不是以这种方式编写的.整个代码位于 Routes Controller 中,否则无法测试.

I can't write unit tests without calling HTTP; the app is not written in such a way. Entire code is in Routes or in Controller is not otherwise testable.

推荐答案

因此,在我的示例中, void 意味着我们的方法不返回任何内容. postJson 意味着我们希望得到 JSON 响应,我们可以只执行 $ this-> post()

So in my example void means that our method does not returning anything.postJson means we expect JSON response, either we can do just $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

    }

这篇关于phpunit中的Laravel REST API测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 17:06