mercredi 3 février 2016

How to preemptively mock a class that gets instantiated by another class

I suspect the "best" answer to my question is to use dependency injection and avoid the issue entirely. Unfortunately I don't have that option...

I need to write a test for a class which causes a third party library to be instantiated. I want to mock/stub the library class so that it doesn't make live API calls.

I'm using phpunit in the CakePHP v3.x framework. I'm able to mock the library and created stub responses, but this doesn't prevent the "real" class from being instantiated by code outside of my test. I considered trying to mock the class(s) upstream from the instantiation, but there are a lot of them, which would make the test incredibly unwieldy to write/maintain.

Is there a way to somehow "stub" the instantiation of the class? Similar to the way we can tell php unit to expect an API call and preset the returned data?

Aucun commentaire:

Enregistrer un commentaire