I want to mock a method in the same class that I am testing.
ClassA {
function hardToTest($arg) {
// difficult to test code
}
function underTest() {
return $this->hardToTest('foo');
}
}
I was thinking that I could use reflection to do this, but maybe it is just a sign that I should move hardToTest
into another object.
We can mock runInGround(String location) method inside the PersonTest class as shown below. Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows.
@InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock annotations into this instance. @Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class.
The simplest and most common way of creating a mock is jest. fn() method. If no implementation is provided, it will return the undefined value. There is plenty of helpful methods on returned Jest mock to control its input, output and implementation.
This test will succeed if underTest()
passes 'foo'
to hardToTest()
. This is known as a partial mock in PHPUnit's documentation because you are mocking only some of the methods.
ClassATest { function testUnderTest() { $mock = $this->getMock('ClassA', ['hardToTest']); $mock->expects($this->once()) ->method('hardToTest') ->with('foo'); $mock->underTest(); } }
I agree with your instincts that this need may be a code smell telling you that this class is doing too much.
PHPUnit 5.4+
Since getMock()
was deprecated in 5.4, use getMockBuilder()
instead:.
$mock = $this->getMockBuilder('ClassA') ->setMethods(['hardToTest']) // onlyMethods in 8.4+ ->getMock();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With