PHPUnit 테스트의 모의 객체 이해

DDD
풀어 주다: 2024-09-22 16:17:02
원래의
413명이 탐색했습니다.

Understanding Mock Objects in PHPUnit Testing

단위 테스트를 작성할 때 중요한 과제는 테스트가 외부 시스템이나 종속성의 간섭 없이 테스트 중인 코드에 초점을 맞추도록 하는 것입니다. 이것이 PHPUnit에서 모의 객체가 작동하는 곳입니다. 이를 통해 제어된 방식으로 실제 객체의 동작을 시뮬레이션할 수 있으므로 테스트가 더욱 안정적이고 유지 관리가 쉬워집니다. 이 기사에서는 모의 객체가 무엇인지, 왜 유용한지, PHPUnit에서 효과적으로 사용하는 방법을 살펴보겠습니다.

모의 객체란 무엇입니까?

모의 객체는 단위 테스트에 사용되는 실제 객체의 시뮬레이션 버전입니다. 다음을 수행할 수 있습니다.

  • 테스트 중인 코드 격리: 모의 객체는 종속성의 동작을 시뮬레이션하여 테스트 결과가 해당 종속성의 실제 구현에 영향을 받지 않도록 합니다.
  • 컨트롤 종속성 동작: 특정 메서드가 호출될 때 모의 객체가 어떻게 동작해야 하는지 지정할 수 있으므로 다양한 시나리오를 테스트할 수 있습니다.
  • 상호작용 확인: 모의 추적 메서드 호출 및 해당 매개변수를 사용하여 테스트 중인 코드가 종속성과 올바르게 상호작용하는지 확인합니다.

모의 객체를 사용하는 이유는 무엇입니까?

모의는 다음 시나리오에서 특히 유용합니다.

  • 복잡한 종속성: 코드가 데이터베이스, API 또는 타사 서비스와 같은 외부 시스템에 의존하는 경우 모의 객체는 해당 시스템과 상호 작용할 필요를 제거하여 테스트를 단순화합니다.
  • 상호작용 테스트: Mock을 사용하면 특정 메소드가 올바른 인수로 호출되는지 확인하여 코드가 예상대로 작동하는지 확인할 수 있습니다.
  • 더 빠른 테스트 실행: 데이터베이스 쿼리나 API 요청과 같은 실제 작업으로 인해 테스트 속도가 느려질 수 있습니다. 이러한 종속성을 모의하면 테스트 실행 속도가 빨라집니다.

스터빙과 모킹: 차이점은 무엇입니까?

모의 객체로 작업할 때 스터빙모의이라는 두 가지 용어를 접하게 됩니다.

  • 스터빙: 모의 객체에 대한 메서드 동작을 정의하는 것을 의미합니다(예: 특정 값을 반환하도록 메서드에 지시).
  • 모의: 메서드 호출 방법에 대한 기대치를 설정하는 작업(예: 메서드 호출 횟수와 해당 매개변수 확인)이 포함됩니다.

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 인수'))는 메소드가 올바른 인수로 호출되었는지 확인합니다.

예: PaymentProcessor를 사용한 테스트

모의 객체의 실제 적용을 보여주기 위해 외부 PaymentGateway 인터페이스에 의존하는 PaymentProcessor 클래스의 예를 들어보겠습니다. 우리는 PaymentGateway의 실제 구현에 의존하지 않고 PaymentProcessor의 processPayment 메소드를 테스트하고 싶습니다.

PaymentProcessor 클래스는 다음과 같습니다.

class PaymentProcessor
{
    private $gateway;

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

    public function processPayment(float $amount): bool
    {
        return $this->gateway->charge($amount);
    }
}
로그인 후 복사

이제 실제 결제 게이트웨이와 상호작용하지 않고 processPayment 방법을 테스트하기 위해 PaymentGateway에 대한 모의를 생성할 수 있습니다.

모의 객체를 사용하여 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!