9951 explained code solutions for 126 technologies


phpunitHow to use getMockBuilder with PHPUnit?


Using getMockBuilder with PHPUnit allows you to create a mock object of a class or interface. This mock object can be used to test the behavior of a class or interface without having to create a real instance of it.

Example

$mock = $this->getMockBuilder(MyClass::class)
    ->setMethods(['myMethod'])
    ->getMock();

This example creates a mock object of the MyClass class with the myMethod method mocked.

Code explanation

  • $this->getMockBuilder(MyClass::class): creates a mock object of the MyClass class.
  • ->setMethods(['myMethod']): mocks the myMethod method.
  • ->getMock(): returns the mock object.

Helpful links

Edit this code on GitHub