0

I have this example class

class Class
{
    public function getStuff()
    {
        $data = $this->getData('Here');

        $data2 = $this->getData('There');

        return $data . ' ' . $data2;
    }

    public function getData( $string )
    {
        return $string;
    }
}

I want to be able to test the getStuff method and mock the getData method.

What would be the best way of mocking this method?

Thanks

1 Answer 1

3

I think the getData method should be part of a different class, separating data from logic. You could then pass a mock of that class to the TestClass instance as a dependency:

class TestClass
{
  protected $repository;

  public function __construct(TestRepository $repository) {
    $this->repository = $repository;
  }

  public function getStuff()
  {
    $data  = $this->repository->getData('Here');
    $data2 = $this->repository->getData('There');

    return $data . ' ' . $data2;
  }
}

$repository = new TestRepositoryMock();
$testclass  = new TestClass($repository);

The mock would have to implement a TestRepository interface. This is called dependency injection. E.g.:

interface TestRepository {
  public function getData($whatever);
}

class TestRepositoryMock implements TestRepository {
  public function getData($whatever) {
    return "foo";
  }
}

The advantage of using an interface and enforcing it in the TestClass constructor method is that an interface guarantees presence of certain methods that you define, like getData() above - whatever the implementation is, the method must be there.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Gargon, that sounds like a good solution. How would this be done using the PHPUnit Mock Objects?
I think it's $mock = $this->getMock('TestRepository');. Refer to the PHPUnit documentation for more examples

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.