Skip to content

Deprecate TestCase::getMockForAbstractClass() #5241

Closed
@sebastianbergmann

Description

@sebastianbergmann

PHPUnit can automatically generate test stubs and mock objects (test doubles) based on interfaces and classes.

When it comes to doubling classes, there are limitations:

  • final, private, and static methods cannot be doubled; they retain their original behavior except for static methods which will be replaced by a method throwing an exception
  • Enumerations (enum) are final classes and therefore cannot be doubled
  • readonly classes cannot be extended by classes that are not readonly and therefore cannot be doubled

Not only because of the limitations mentioned above, but also to improve your software design, PHPUnit's documentation recommends to favour the doubling of interfaces over the doubling of classes.

For quite a while, PHPUnit has offered the createStub() and createMock() methods for creating test stubs and mock objects with best practice defaults. Furthermore, alternatives such as getMockForAbstractClass() exist, but not all of them offer the same clear separation between test double and mock object. For instance, no method named getStubForAbstractClass() exists. Such an inconsistency can lead to confusion.

As its name suggests, the getMockForAbstractClass() method can be used to create a mock object for an abstract class: a mock object where all abstract methods of the original class are implemented in such a way that they can be configured to return a specified value, for instance, or to expect an invocation.

Having to use getMockForAbstractClass() to test something is almost always a code smell: something is not quite right with the software design of the system-under-test.

To promote better software design, improve the readability of test code, and to reduce complexity inside PHPUnit's test double functionality, TestCase::getMockForAbstractClass() will be deprecated and then removed:

  • soft deprecation in PHPUnit 10.1 (add @deprecated annotation to the method declaration)
  • deprecation in PHPUnit 11 (using the method will trigger a deprecation)
  • removal in PHPUnit 12

Metadata

Metadata

Labels

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions