前言
当前使用Laravel8.x 一代版本一代神
创建测试文件
php artisan make:test UserTest
运行测试
# 测试 tests/Feature 下所有测试文件
# 不符合预期则输出具体位置&差异
php artisan test --testsuite=Feature --stop-on-failure
DatabaseTransactions
http测试
$this->"method"("url","params","headers")
$response->assertStatus(200);
$response->assertJson(['code' => 10001]);
常用断言
$this->assertEquals("value1","value2","message");
$this->assertNotEquals("value1","value2","message");
$this->assertEmpty("value","message");
$this->assertNotNull("value","message");
$this->assertContains("value","haystack");
$this->assertContains('a', [0 => 'a']);
添加测试数据
php artisan make:factory “工厂类名” --model=“对应的数据库模型”
php artisan make:factory UserFactory --model=App/Models/Auth/User
namespace Database\Factories;
use App\Models\Auth\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory
{
protected $model = User::class;
public function definition()
{
return [
'name' => $this->faker->name,
'mobile' => $this->faker->phoneNumber,
'password' => $this->faker->password,
'creator' => 1,
'updater' => 1,
'created_at' => now(),
'updated_at' => now(),
];
}
}
$this->faker 提供了生成数据内容的方法 介绍常用方法
'faker_locale' => 'zh_CN'
$this->faker->name;
$this->faker->phoneNumber;
$this->faker->email;
$this->faker->imageUrl;
数据工厂类的使用 单表创建
UserFactory::new()->count(10)->create();
namespace Tests\Feature;
use Database\Factories\UserFactory;
use Tests\TestCase;
class UserTest extends TestCase
{
public function test_example()
{
UserFactory::new()->count(10)->create();
$this->assertNotNull("successful");
}
}
关联创建
PostFactory
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
public function definition()
{
return [
'title' => $this->faker->title,
'created_at' => now(),
'updated_at' => now(),
];
}
}
填充两张表数据
namespace Tests\Feature;
use Database\Factories\PostFactory;
use Database\Factories\UserFactory;
use Tests\TestCase;
class UserTest extends TestCase
{
public function test_example()
{
UserFactory::new()->count(10)->afterCreating(function ($user) {
PostFactory::new()->count(1)->state(function () use ($user) {
return ['user_id' => $user->id];
})->create();
})->create();
$this->assertNotNull("successful");
}
}
|