
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | use PHPUnit\Framework\TestCase;
class MyTest extends TestCase
{
public function testMockExample()
{
$mock = $this ->createMock(SomeClass:: class );
$mock ->method( 'someMethod' )
->willReturn( 'mocked value' );
$unitUnderTest = new ClassUnderTest( $mock );
$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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public function testMethodCallVerification()
{
$mock = $this ->createMock(SomeClass:: class );
$mock ->expects( $this ->once())
->method( 'someMethod' )
->with( $this ->equalTo( 'expected argument' ))
->willReturn( 'mocked value' );
$unitUnderTest = new ClassUnderTest( $mock );
$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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | use PHPUnit\Framework\TestCase;
class PaymentProcessorTest extends TestCase
{
public function testProcessPayment()
{
$gatewayMock = $this ->createMock(PaymentGateway:: class );
$gatewayMock ->method( 'charge' )
->with(100.0)
->willReturn(true);
$paymentProcessor = new PaymentProcessor( $gatewayMock );
$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:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public function testProcessPaymentCallsCharge()
{
$gatewayMock = $this ->createMock(PaymentGateway:: class );
$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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | use PHPUnit\Framework\TestCase;
class UserServiceTest extends TestCase
{
public function testGetUserName()
{
$mockRepo = $this ->createMock(UserRepository:: class );
$mockRepo ->method( 'find' )
->willReturn((object) [ 'name' => 'John Doe' ]);
$service = new UserService( $mockRepo );
$this ->assertEquals( 'John Doe' , $service ->getUserName(1));
}
}
|
Salin selepas log masuk
Best Practices for Using Mocks
-
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.
-
Focus on Behavior, Not Implementation: Mocks should help test the behavior of your code, not the specific implementation details of dependencies.
-
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.
-
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!