bg_image
header

Partial Mock

A Partial Mock is a testing technique where only certain methods of an object are mocked, while the rest of the object retains its real implementation. This is useful when you want to stub or mock specific methods but keep others functioning normally.

When to Use a Partial Mock?

  • When you want to test a class but isolate certain methods.

  • When some methods are difficult to test (e.g., they have external dependencies), but others should retain their real logic.

  • When you only need to stub specific methods to control test behavior.

Example in PHP with PHPUnit

Suppose you have a Calculator class but want to mock only the multiply() method while keeping add() as is.

class Calculator {
    public function add($a, $b) {
        return $a + $b;
    }

    public function multiply($a, $b) {
        return $a * $b;
    }
}

// PHPUnit Test with Partial Mock
class CalculatorTest extends \PHPUnit\Framework\TestCase {
    public function testPartialMock() {
        // Create a Partial Mock for Calculator
        $calculator = $this->getMockBuilder(Calculator::class)
                           ->onlyMethods(['multiply']) // Only mock this method
                           ->getMock();

        // Define behavior for multiply()
        $calculator->method('multiply')->willReturn(10);

        // Test real add() method
        $this->assertEquals(5, $calculator->add(2, 3));

        // Test mocked multiply() method
        $this->assertEquals(10, $calculator->multiply(2, 3));
    }
}

Here, add() remains unchanged and executes the real implementation, while multiply() always returns 10.

Conclusion

Partial Mocks are useful when you need to isolate specific parts of a class without fully replacing it. They help make tests more stable and efficient by mocking only selected methods.


Created 3 Days 14 Hours ago
Applications Integration Tests Class Method Mock Object PHPUnit Partial Mock Principles Programming Software Strategies Stub System Under Test - SUT Testing Unit Tests Web Development

Leave a Comment Cancel Reply
* Required Field