John Davidson

php - MockBuilder doesn't see method in Interface


I'm trying to mock Throwable interface but MockBuilder doesn't see getPrevious() method.

    $throwableMock = $this->getMockBuilder(\Throwable::class)


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)

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:

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
->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 5042 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us