3

In phpspec can i mock the return value of a method?

for example:

class MyClass()
{
    public function getStaffMemberNames()
    {
        // db call to get array of staff member names
    }

    public function sortStaffMemberNames()
    {
        return sort($this->getStaffMemberNames());
    }
}

I am interested in testing the sortStaffMemberNames method. But it relies on another class method which uses a db connection. I want to mock the getStaffMemberNames so i can easily test.

How can this be achieved?

Marty Wallace
  • 34,046
  • 53
  • 137
  • 200

1 Answers1

3

There's no partial mocks in phpspec (you cannot mock the class under test). This is a bad practice.

You should mock your collaborators instead (database connection for example).

Jakub Zalas
  • 35,761
  • 9
  • 93
  • 125
  • Bad practice? So it's better to mock the database call in every single method that uses the method getStaffMemberNames()? – martindilling Mar 14 '14 at 03:13
  • 1
    phpspec tries to enforce some practices, amongst them the Single Responsibility Principle. In your case, "sortStaffMemberNames()" has its own responsibility (sorting) and should be extracted into a new object and receive the result of "getStaffMemberNames" as a parameter. – Loïc Faugeron Feb 18 '15 at 10:54
  • Exactly. Whenever something is getting hard with phpspec, it indicates you've got a design issue. – Jakub Zalas Feb 18 '15 at 12:07