rgazelot
rgazelot

Reputation: 538

Is it possible to mock our own service?

I want to mock a service that is required in a class constructor. I have an exception of PHPUnit : MyService is required, Mock_MyService_0afc7fc1 given.

But with the Request, EntityManager or other Symfony 2 component, I haven't this issue.

Here is my Class's construct :

use Acme\Bundle\Service\MyService;
use Symfony\Component\HttpFoundation\Request;

...

public function __construct(MyService $service, Request $request)
{

and my mock :

...

$service = $this->getMock('MyService');

$class = new Class($service, $request);

It's impossible to mock our own service ? Only Symfony 2 component ?

PS : If I delete MyServicelike that : public function __construct($service, Request $request), this works. But I want to define my variable with it :(

Upvotes: 1

Views: 365

Answers (1)

edorian
edorian

Reputation: 38961

The issue is that PHPUnit at the time of the test execution can't find (or autoload) your MyService class.

That means that you'll probably run into the same issues with other Mocking libraries as all of them require the original class to exist to scan it and create the mock.

It happens because you need to tell PHPUnit the Fully-Qualified Class Name.

Change your code to $this->getMock("\Acme\Bundle\Service\MyService"); and it should work out.

(Still, give mockery a try. It's a nice library)

Upvotes: 1

Related Questions