简体   繁体   中英

How To Mock These Methods With PHPUnit?

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

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. Eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM