user2718704
user2718704

Reputation: 803

Symfony Mock a specific method in my unit test

I have problem when trying to mock a service in order to unit test it.

in my test class I have,

    $mock = $this->getMock('MyClass');
    $mock->expects($this->any())->method('method_2')->will($this->returnValue('fake_value'));

in my service, method_2() calls another method (let's say method_1()')

As I want to unit test only method_1() I need to mock only method_2() but when I am running this test, method_1() already returns null.

Do you have any idea on why I'm already getting null?

Upvotes: 1

Views: 1992

Answers (1)

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

Take a look at getMock() helper signature, it allows you to pass an array of methods as a second argument, those methods are then mocked and returns null (unless you define the valus each one of them should return)

In your case all the methods are mocked and return null except method_2() for which you forced the returned value.

Try again and replace,

$mock = $this->getMock('MyClass');

by,

$mock = $this->getMock('MyClass', array('method_2'));

Upvotes: 1

Related Questions