首頁  >  文章  >  後端開發  >  了解 PHPUnit 測試中的模擬對象

了解 PHPUnit 測試中的模擬對象

DDD
DDD原創
2024-09-22 16:17:02542瀏覽

Understanding Mock Objects in PHPUnit Testing

編寫單元測試時,一個關鍵挑戰是確保您的測試專注於被測程式碼,而不受外部系統或依賴項的干擾。這就是模擬物件在PHPUnit中發揮作用的地方。它們允許您以受控方式模擬真實物件的行為,使您的測試更可靠且更易於維護。在本文中,我們將探討什麼是模擬物件、它們為何有用以及如何在 PHPUnit 中有效地使用它們。

什麼是模擬物件?

模擬物件是在單元測試中使用的真實物件的模擬版本。它們允許您:

  • 隔離被測程式碼:模擬物件模擬依賴項的行為,確保測試結果不受這些依賴項實際實現的影響。
  • 控制依賴行為:您可以指定在呼叫某些方法時模擬應如何表現,使您能夠測試不同的場景。
  • 驗證互動:模擬追蹤方法呼叫及其參數,確保被測試的程式碼與其依賴項正確互動。

為什麼要使用模擬物件?

模擬在以下場景特別有用:

  • 複雜的依賴關係:如果您的程式碼依賴資料庫、API 或第三方服務等外部系統,則模擬物件可以透過消除與這些系統互動的需要來簡化測試。
  • 互動測試:模擬可讓您驗證是否使用正確的參數呼叫特定方法,確保您的程式碼能如預期運作。
  • 更快的測試執行:資料庫查詢或 API 請求等實際操作可能會減慢測試速度。模擬這些依賴項可確保更快的測試執行。

存根與模擬:有什麼差別?

使用模擬物件時,您會遇到兩個術語:stubbingmocking:

  • 存根:指在模擬物件上定義方法的行為,例如指示方法傳回特定值。
  • 模擬:涉及設定對如何呼叫方法的期望,例如驗證方法呼叫的數量及其參數。

如何在 PHPUnit 中建立和使用模擬對象

PHPUnit 透過 createMock() 方法可以輕鬆建立和使用模擬物件。以下是一些範例,示範如何有效地使用模擬物件。

範例 1:基本模擬物件用法

在此範例中,我們為類別依賴項建立一個模擬物件並指定其行為。

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);
    }
}

說明

  • createMock(SomeClass::class) 為 SomeClass 建立一個模擬物件。
  • method('someMethod')->willReturn('mocked value') 定義模擬的行為。
  • 模擬物件被傳遞給正在測試的類,確保不使用真正的 SomeClass 實作。

範例 2:驗證方法調用

有時,您需要驗證是否使用正確的參數呼叫了方法。具體方法如下:

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();
}

重點

  • Expects($this->once()) 確保 someMethod 被呼叫一次。
  • with($this->equalTo('expected argument')) 驗證是否使用正確的參數呼叫該方法。

範例:使用 PaymentProcessor 進行測試

為了示範模擬物件的實際應用,我們以依賴外部 PaymentGateway 介面的 PaymentProcessor 類別為例。我們想要測試 PaymentProcessor 的 processPayment 方法,而不依賴 PaymentGateway 的實際實作。

這是 PaymentProcessor 類別:

class PaymentProcessor
{
    private $gateway;

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

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

現在,我們可以為 PaymentGateway 建立一個模擬來測試 processPayment 方法,而無需與實際的支付網關互動。

使用模擬物件測試 PaymentProcessor

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));
    }
}

檢定分解

  • 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);
}

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;
    }
}

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));
    }
}

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

以上是了解 PHPUnit 測試中的模擬對象的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn