Laravel Unit Test - Test Job

Bài này thì cơ bản về cách test 1 job được đưa vào hàng đợi hay chưa? và test mock service của một bên thứ 3 như thế nào


1. Import những thư viện cần thiết:
use Bus;
use Illuminate\Testing\Fluent\AssertableJson;
use Mockery;
use Mockery\MockInterface;

Trong đó thì: 
- Bus dùng để gửi một lệnh đến trình xử lý thích hợp của nó.
- AssertableJson dùng để kiểm tra kết quả trả về
- Mockery dùng để mock các dịch vụ của bên thứ 3
- MockInterface dùng để định nghĩa định dạng

2. Gọi function test
public function test_user_can_check_device_but_dont_know_serial()
{
    // Giả lập môi trường sẽ gởi lệnh
    Bus::fake();

    // Gọi đến dịch vụ của bên thứ 3
    $this->instance(
        MSService::class,
            Mockery::mock(MSService::class, function (MockInterface $mock) {
                $mock->shouldReceive('requestToTenant') // function nào được gọi
                    ->withAnyArgs() // Chấp nhận mọi tham số
                    ->once() // Ngụ ý gọi 1 lần
                    ->andReturnSelf(); // Trả về chính nó

                $mock->shouldReceive('importAutopilotDeviceIdentity')
                    ->withAnyArgs()
                    ->once()
                    ->andReturn(new ImportedWindowsAutopilotDeviceIdentity());
            })
        );

    // Khởi tạo giá trị
    $data = [
        'serial' => '2aaNN4',
        'external_id' => 998,
        'hash' => '123-TEST-HASH'
    ];
    
    // Gọi API
    $response = $this->postJson('/api/external/check-data', $data);

    // Gọi Hàm assertDispatched để giả lập đưa job vào hàng đợi
    Bus::assertDispatched(CaptureIntuneCheckImportStatusJob::class);

    // Kiểm tra kết quả trả về
    $response->assertStatus(200)->assertJson(function (AssertableJson $json) {
        $json
            ->has('success')
            ->has('success-code')
            ->where('success-code', 0)    
            ->has('message')
            ->where('message', 'Request still in progress');
    });
    // Chú ý khi thực hiện xong công việc thì nên đóng Mockery lại
    Mockery::close();
}

Comments

Bài đăn phổ biến

Deploy website lên VPS hoặc Hosting với Gitlab CI/CD

MỞ CAMERA VÀ CHỤP ẢNH BẰNG PHP

Tính Bình Phương 1 Số Trong Python

Đường dẫn tương đối trong Java