PHP Unit Test: How to test a class that implements an interface from another package?

StackOverflow https://stackoverflow.com/questions/23301418

  •  09-07-2023
  •  | 
  •  

Question

I am trying to test a class that implements an interface that is defined outside the scope of the classes package (i.e. I pull it in as a dependency using composer during integration).

I would like to test this concrete class without having to pull in the interface it depends on. Is there anyway to test this in php unit test?

At the moment I can't even instantiate an instance as the interface is obviously not found.

Was it helpful?

Solution

The interface that your class is not a dependency in that sense... There is nothing to mock. You just need to make sure that the class is an instance of the interface in your tests for that class.

You need to change something about your testing environment so that the interface is available in order to test your class. So that you can instantiate and test the behavior of the methods that the interface specifies.

Dependency injection is about objects that your code NEEDS not what your code is. An interface or an abstract class are not dependencies. Even though your code "depends" on those things existing.

Dependencies are external objects that you class needs to do something. Interfaces and abstract classes define what are you class is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top