Memahami Objek Olok-olok dalam Pengujian PHPUnit

DDD
Lepaskan: 2024-09-22 16:17:02
asal
413 orang telah melayarinya

Understanding Mock Objects in PHPUnit Testing

Apabila menulis ujian unit, cabaran utama ialah memastikan ujian anda memfokus pada kod yang sedang diuji tanpa gangguan daripada sistem luaran atau kebergantungan. Di sinilah objek olok-olok berperanan dalam PHPUnit. Mereka membenarkan anda mensimulasikan kelakuan objek sebenar dengan cara terkawal, menjadikan ujian anda lebih dipercayai dan lebih mudah untuk diselenggara. Dalam artikel ini, kami akan meneroka apakah objek olok-olok, sebab ia berguna dan cara menggunakannya dengan berkesan dalam PHPUnit.

Apakah Objek Olok-olok?

Objek olok-olok ialah versi simulasi objek sebenar digunakan dalam ujian unit. Mereka membenarkan anda untuk:

  • Asingkan Kod Dalam Ujian: Objek olok-olok mensimulasikan gelagat tanggungan, memastikan keputusan ujian tidak terjejas oleh pelaksanaan sebenar tanggungan tersebut.
  • Kawal Tingkah Laku Kebergantungan: Anda boleh menentukan cara olok-olok itu harus berkelakuan apabila kaedah tertentu dipanggil, membolehkan anda menguji senario yang berbeza.
  • Sahkan Interaksi: Mengejek panggilan kaedah jejak dan parameternya, memastikan kod yang sedang diuji berinteraksi dengan betul dengan kebergantungannya.

Mengapa Menggunakan Objek Olok-olok?

Olok-olok amat berguna dalam senario berikut:

  • Ketergantungan Kompleks: Jika kod anda bergantung pada sistem luaran seperti pangkalan data, API atau perkhidmatan pihak ketiga, objek olok-olok memudahkan ujian dengan menghapuskan keperluan untuk berinteraksi dengan sistem tersebut.
  • Ujian Interaksi: Olok-olok membolehkan anda mengesahkan bahawa kaedah tertentu dipanggil dengan hujah yang betul, memastikan kod anda berkelakuan seperti yang diharapkan.
  • Pelaksanaan Ujian yang Lebih Pantas: Operasi dunia sebenar seperti pertanyaan pangkalan data atau permintaan API boleh melambatkan ujian. Mengejek kebergantungan ini memastikan pelaksanaan ujian yang lebih pantas.

Stubbing vs. Mengejek: Apakah Perbezaannya?

Apabila bekerja dengan objek olok-olok, anda akan menjumpai dua istilah: mengejek dan mengejek:

  • Stubbing: Merujuk kepada mentakrifkan kelakuan kaedah pada objek olok-olok, cth., mengarahkan kaedah untuk mengembalikan nilai tertentu.
  • Mengejek: Melibatkan penetapan jangkaan tentang cara kaedah harus dipanggil, cth., mengesahkan bilangan panggilan kaedah dan parameternya.

Cara Mencipta dan Menggunakan Objek Olok-olok dalam PHPUnit

PHPUnit memudahkan untuk mencipta dan menggunakan objek olok-olok dengan kaedah createMock(). Di bawah ialah beberapa contoh yang menunjukkan cara bekerja dengan objek olok-olok dengan berkesan.

Contoh 1: Penggunaan Objek Olok-olok Asas

Dalam contoh ini, kami mencipta objek olok-olok untuk pergantungan kelas dan menentukan kelakuannya.

use PHPUnit\Framework\TestCase;

class MyTest extends TestCase
{
    public function testMockExample()
    {
        // Create a mock for the SomeClass dependency
        $mock = $this->createMock(SomeClass::class);

        // Specify that when the someMethod method is called, it returns 'mocked value'
        $mock->method('someMethod')
             ->willReturn('mocked value');

        // Pass the mock object to the class under test
        $unitUnderTest = new ClassUnderTest($mock);

        // Perform the action and assert that the result matches the expected value
        $result = $unitUnderTest->performAction();
        $this->assertEquals('expected result', $result);
    }
}
Salin selepas log masuk

Penjelasan:

  • createMock(SomeClass::class) mencipta objek olok-olok untuk SomeClass.
  • method('someMethod')->willReturn('mocked value') mentakrifkan tingkah laku olok-olok.
  • Objek olok-olok dihantar ke kelas yang sedang diuji, memastikan pelaksanaan SomeClass sebenar tidak digunakan.

Contoh 2: Mengesahkan Panggilan Kaedah

Kadangkala, anda perlu mengesahkan bahawa kaedah dipanggil dengan parameter yang betul. Begini cara anda boleh melakukannya:

public function testMethodCallVerification()
{
    // Create a mock object
    $mock = $this->createMock(SomeClass::class);

    // Expect the someMethod to be called once with 'expected argument'
    $mock->expects($this->once())
         ->method('someMethod')
         ->with($this->equalTo('expected argument'))
         ->willReturn('mocked value');

    // Pass the mock to the class under test
    $unitUnderTest = new ClassUnderTest($mock);

    // Perform an action that calls the mock's method
    $unitUnderTest->performAction();
}
Salin selepas log masuk

Isi Penting:

  • expects($this->once()) memastikan someMethod dipanggil tepat sekali.
  • with($this->equalTo('expected argument')) mengesahkan bahawa kaedah dipanggil dengan hujah yang betul.

Contoh: Menguji dengan PaymentProcessor

Untuk menunjukkan aplikasi dunia sebenar bagi objek olok-olok, mari kita ambil contoh kelas PaymentProcessor yang bergantung pada antara muka PaymentGateway luaran. Kami ingin menguji kaedah processPayment PaymentProcessor tanpa bergantung pada pelaksanaan sebenar PaymentGateway.

Berikut ialah kelas PaymentProcessor:

class PaymentProcessor
{
    private $gateway;

    public function __construct(PaymentGateway $gateway)
    {
        $this->gateway = $gateway;
    }

    public function processPayment(float $amount): bool
    {
        return $this->gateway->charge($amount);
    }
}
Salin selepas log masuk

Kini, kami boleh membuat olok-olok untuk PaymentGateway untuk menguji kaedah processPayment tanpa berinteraksi dengan gerbang pembayaran sebenar.

Menguji PaymentProcessor dengan Objek Olok-olok

use PHPUnit\Framework\TestCase;

class PaymentProcessorTest extends TestCase
{
    public function testProcessPayment()
    {
        // Create a mock object for the PaymentGateway interface
        $gatewayMock = $this->createMock(PaymentGateway::class);

        // Define the expected behavior of the mock
        $gatewayMock->method('charge')
                    ->with(100.0)
                    ->willReturn(true);

        // Inject the mock into the PaymentProcessor
        $paymentProcessor = new PaymentProcessor($gatewayMock);

        // Assert that processPayment returns true
        $this->assertTrue($paymentProcessor->processPayment(100.0));
    }
}
Salin selepas log masuk

Pecahan Ujian:

  • createMock(PaymentGateway::class) creates a mock object simulating the PaymentGateway interface.
  • method('charge')->with(100.0)->willReturn(true) specifies that when the charge method is called with 100.0 as an argument, it should return true.
  • The mock object is passed to the PaymentProcessor class, allowing you to test processPayment without relying on a real payment gateway.

Verifying Interactions

You can also verify that the charge method is called exactly once when processing a payment:

public function testProcessPaymentCallsCharge()
{
    $gatewayMock = $this->createMock(PaymentGateway::class);

    // Expect the charge method to be called once with the argument 100.0
    $gatewayMock->expects($this->once())
                ->method('charge')
                ->with(100.0)
                ->willReturn(true);

    $paymentProcessor = new PaymentProcessor($gatewayMock);
    $paymentProcessor->processPayment(100.0);
}
Salin selepas log masuk

In this example, expects($this->once()) ensures that the charge method is called exactly once. If the method is not called, or called more than once, the test will fail.

Example: Testing with a Repository

Let’s assume you have a UserService class that depends on a UserRepository to fetch user data. To test UserService in isolation, you can mock the UserRepository.

class UserService
{
    private $repository;

    public function __construct(UserRepository $repository)
    {
        $this->repository = $repository;
    }

    public function getUserName($id)
    {
        $user = $this->repository->find($id);
        return $user->name;
    }
}
Salin selepas log masuk

To test this class, we can mock the repository:

use PHPUnit\Framework\TestCase;

class UserServiceTest extends TestCase
{
    public function testGetUserName()
    {
        // Create a mock for the UserRepository
        $mockRepo = $this->createMock(UserRepository::class);

        // Define that the find method should return a user object with a predefined name
        $mockRepo->method('find')
                 ->willReturn((object) ['name' => 'John Doe']);

        // Instantiate the UserService with the mock repository
        $service = new UserService($mockRepo);

        // Assert that the getUserName method returns 'John Doe'
        $this->assertEquals('John Doe', $service->getUserName(1));
    }
}
Salin selepas log masuk

Best Practices for Using Mocks

  1. Use Mocks Only When Necessary: Mocks are useful for isolating code, but overuse can make tests hard to understand. Only mock dependencies that are necessary for the test.
  2. Focus on Behavior, Not Implementation: Mocks should help test the behavior of your code, not the specific implementation details of dependencies.
  3. Avoid Mocking Too Many Dependencies: If a class requires many mocked dependencies, it might be a sign that the class has too many responsibilities. Refactor if needed.
  4. Verify Interactions Sparingly: Avoid over-verifying method calls unless essential to the test.

Conclusion

Mock objects are invaluable tools for writing unit tests in PHPUnit. They allow you to isolate your code from external dependencies, ensuring that your tests are faster, more reliable, and easier to maintain. Mock objects also help verify interactions between the code under test and its dependencies, ensuring that your code behaves correctly in various scenarios

Atas ialah kandungan terperinci Memahami Objek Olok-olok dalam Pengujian PHPUnit. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!