Изучаем вопрос покрытия тестами того, что уже написано … Пишем свой тест-case

/**/

Примеры

Пример теста (1):

Тебе надо протестировать запросы к api, в этом случае просто чекаешь response примерно так

$response = $this->post('/api/upload');
        $response
            ->assertStatus(200)
            ->assertExactJson([
                'code' => 200,
                'output' => [],
            ]);
        ;

+ Читаем документашку в (2)

Демо-тест

(звезда) демо-тесты в Laravel лежат тут: apptestsExampleTest.php

Запускаем демо-тест: (в windows/openserver — путь через обратные слеши):

vendorbinphpunit

Демо-тест провалился:

Time: 00:07.939, Memory: 20.00 MB

There was 1 failure:

1) TestsFeatureExampleTest::test_example
Expected status code 200 but received 302.
Failed asserting that 200 is identical to 302.

E:OpenServerOSPaneldomainslocalhostvendorlaravelframeworksrcIlluminateTestingTestResponse.php:187
E:OpenServerOSPaneldomainslocalhosttestsFeatureExampleTest.php:19

FAILURES!
Tests: 2, Assertions: 2, Failures: 1.

Ок, правим его как нам надо:

в файле tests/Feature/ExampleTest.php

        $response = $this->get('/');
===>
        $response = $this->get('http://localhost/tasks');

Ок, тест сработал:

Напишем теперь свой тест …

Пишу свой тест

Например, напишем тест для реально важных кусков (где могут быть ошибки):

Тест для Subtask.calcSupplierPrice

Будем тестировать данный метод:

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Subtask extends Model
{
    use HasFactory;

    // (...)

    /**
     * Get price from price-list, stored in 'task_price' table
     * @param $service_type_id
     * @param $task_type_id
     * @param $speed
     * @return int
     */
    public function calcSupplierPrice()
    {
        $price = TaskPrice::orderBy('id')
            ->where('supplier_id', '=', $this->supplier_id)
            ->where('service_type_id', '=', $this->service_type_id)
            ->where('task_type_id', '=', $this->task_type_id)
            ->where('speed', '=', $this->speed)
            ->first();

        return (isset($price->price) ? $price->price : 0);
    }
}

Ошибка:

1) TestsUnitSubtaskTest::testCalcSupplierPrice
Error: Call to a member function connection() on null

Т.е. коннектится к БД testCase не умеет …

Решение (3) :

One more reason check if the test class is extending use TestsTestCase; rather then use PHPUnitFrameworkTestCase;

Laravel ships with the later, but TestsTestCase class take care of setting up the application, otherwise models wont be able to communicate with the database if they are extending PHPunitFrameworkTestCase.

Первый тест-кейс написан: tests/Unit/SubtaskTest.php

<?php

namespace TestsUnit;

use AppModelsSubtask;
use TestsTestCase;

class SubtaskTest extends TestCase
{
    /** @var Subtask Subtask  */
    private $subtask;

    /**
     * Init
     */
    protected function setUp() : void
    {
        parent::setUp();

        $subtask = new Subtask();
        $subtask->service_type_id   = 1;
        $subtask->task_type_id      = 1;
        $subtask->supplier_id       = 2;
        $subtask->speed             = 'fast';
        $subtask->status            = Subtask::STATUS_ERROR;
        $subtask->cnt               = 10;
        $subtask->url               = 'https://www.instagram.com/p/CPeAZ5-rmj0/';

        $this->subtask = $subtask;
    }

    /**
     * Test price calculator
     * @return void
     */
    public function testCalcSupplierPrice()
    {

        $price = $this->subtask->calcSupplierPrice();

        $this->assertEquals(14, $price);      // expected price
    }

    /**
     * Test price calculator
     * @return void
     */
    public function testCalcPrice()
    {
        $price  = $this->subtask->calcSupplierPrice();
        $count = $this->subtask->getCount();

        // calculated here
        $calc_price  = $price * $count;

        // caclulated by Subtask class
        $total_price = $this->subtask->calcPrice();

        $this->assertEquals(140, $total_price);      // expected price
        $this->assertEquals($calc_price, $total_price);      // expected price (2)
    }

}

Источники:

(1) https://qna.habr.com/q/591169

(2) Тестирование в Laravel: https://laravel.com/docs/5.7/testing

(3) https://stackoverflow.com/questions/42512676/laravel-5-unit-test-call-to-a-member-function-connection-on-null

Tags

Нет Ответов

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Рубрики


Подпишись на новости
👋

Есть вопросы?