keenlabs / KeenClient-PHP

Official PHP client for the Keen IO API. Build analytics features directly into your PHP apps.
https://keen.io/docs
MIT License
133 stars 57 forks source link

phpunit lacks support for mocking static methods, how to mock \KeenIO\Client\KeenIOClient? #69

Closed thedavidmeister closed 8 years ago

thedavidmeister commented 9 years ago

I'm getting PHPUnit_Framework_MockObject_BadMethodCallException when trying to mock KeenIOClient as soon as the static factory method is called.

It's obvious that I won't want my unit tests actually hitting real KeenIO endpoints, but I want to test classes that use KeenIOClient, so I want to mock KeenIOClient.

What's the suggested approach here?

thedavidmeister commented 9 years ago

Sometimes a static methods is a factory for other objects. This further exuberates the testing problem. In tests we rely on the fact that we can wire objects differently replacing important dependencies with mocks. Once a new operator is called we can not override the method with a sub-class. A caller of such a static factory is permanently bound to the concrete classes which the static factory method produced. In other words the damage of the static method is far beyond the static method itself. Butting object graph wiring and construction code into static method is extra bad, since object graph wiring is how we isolate things for testing.

Hexodus commented 8 years ago

The above answer is very popular and certainly has good reasons to be told but this is not the final one. You can mock static calls using AspectMock . This is a mocking framework for PHPUnit / Codeception.

stof commented 8 years ago

The only static method in KeenIOClient is the factory method. So the answer to mocking is to inject the instance into your own class instead of making your class instantiate the KeenIOClient itself. This way, you can inject a mock in it, and all methods you would need to mock are non-static ones.

elof commented 8 years ago

Not certain this would be the right thing, but I think https://ngrok.com/ may be helpful here. Closing this because it has been dormant for > a year