laravel:单元测试之model(10.27.0)
一,相关文档
https://learnku.com/docs/laravel/10.x/testing/14895
二,php代码
1,查看laravel自带的phpunit的版本
liuhongdi@lhdpc:/data/laravel/dignews$ ./vendor/bin/phpunit --version
PHPUnit 10.4.1 by Sebastian Bergmann and contributors.
2,创建测试类:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan make:test SUserTest --unit
INFO Test [tests/Unit/SUserTest.php] created successfully.
3,测试类的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<?php namespace Tests\Unit; use Illuminate\Database\Eloquent\Model; //use PHPUnit\Framework\TestCase; use App\Models\SUser; use Tests\TestCase; class SUserTest extends TestCase { /** * A basic unit test example. */ public function test_example(): void { //得到数据 $model = new SUser(); $obj = $model ->getOneById(1); //断言 $userId = $obj [ 'user_id' ]; $userName = $obj [ 'username' ]; $this ->assertEquals(1, $userId ); $this ->assertEquals( 'laoliu' , $userName ); } } |
三,测试效果
liuhongdi@lhdpc:/data/laravel/dignews$ vendor/bin/phpunit --filter=SUserTest
PHPUnit 10.4.1 by Sebastian Bergmann and contributors.
Runtime: PHP 8.1.1
Configuration: /data/laravel/dignews/phpunit.xml
. 1 / 1 (100%)
Time: 00:00.096, Memory: 24.00 MB
OK (1 test, 2 assertions)
四,可能出现的报错:
1,报错
1) Error: Call to a member function connection() on null
2,解决:
在测试类中:
注释掉下面一行,如下
//use PHPUnit\Framework\TestCase;
添加Tests\TestCase,如下,
use Tests\TestCase;
3,原因:
检查测试类,它需要在扩展使用 Tests\TestCase;
而不是使用 PHPUnit\Framework\TestCase;(laravel默认使用的类)
Tests\TestCase类负责设置应用程序,
如果使用PHPunit\Framework\TestCase,模型将无法与数据库通信。
五,查看laravel框架的版本:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0