I'm trying to mock Throwable interface but MockBuilder doesn't see getPrevious() method.
$throwableMock = $this->getMockBuilder(\Throwable::class)
->disableOriginalConstructor()
->getMock();
$throwableMock->method('getPrevious')
->willReturn($domainExceptionMock);
I get this error:
Trying to configure method "getPrevious" which cannot be configured because it does not exist, has not been specified, is final, or is static
If i add addMethods to mock builder, like this:
$throwableMock = $this->getMockBuilder(\Throwable::class)
->addMethods(['getPrevious'])
->disableOriginalConstructor()
->getMock();
I get the following error:
Trying to set mock method "getPrevious" with addMethods(), but it exists in class "Throwable". Use onlyMethods() for methods that exist in the class
What am i doing wrong?
My Answer:
The MockBuilder class in PHP is used to create mock objects for testing purposes. It allows you to specify the methods that you want to mock and set expectations for those methods. This can be useful for testing code that depends on external dependencies, such as databases or APIs, without actually having to interact with those dependencies during testing.
Here is an example of how you can use the MockBuilder class to create a mock object:
php
use PHPUnit\Framework\MockObject\MockBuilder;
// Create a mock builder for a class named MyClass
$mockBuilder = new MockBuilder(MyClass::class);
// Specify the methods that you want to mock
$mockBuilder->setMethods(['method1', 'method2']);
// Build the mock object
$mockObject = $mockBuilder->getMock();
// Set expectations for the mocked methods
$mockObject->expects($this->once())
->method('method1')
->willReturn('mocked result');
// Use the mock object in your test
$result = $mockObject->method1();
// Assert that the method was called with the expected arguments
$this->assertEquals('mocked result', $result);
In this example, we create a mock builder for a class named MyClass and specify that we want to mock the methods method1 and method2. We then build the mock object and set an expectation for the method1 method, specifying that it should be called once and return a mocked result. Finally, we use the mock object in our test and assert that the method was called with the expected arguments.
Overall, the MockBuilder class in PHP is a useful tool for creating mock objects in unit tests and setting expectations for those objects.
Rate this post
3 of 5 based on 7317 votesComments