Is it possible to create a mock outside a test case in PhpUnit?

时光毁灭记忆、已成空白 提交于 2019-12-29 08:41:51

问题


It may seem silly, hope not, but I want to create a service that will return mock objects for people that uses my project so they can mock all the classes from my project and test their code.

My idea was to offer this kind of service so it can be called inside other project's test cases and obtain the appropriate mock for each test.

Is that possible? Or there are other ways to do that. Btw, I can't use any mocking library because of project's limitations.


回答1:


Yes, it is possible. Under the hood the getMock method uses the PHPUnit_Framework_MockObject_Generator class. So you can use it directly:

PHPUnit_Framework_MockObject_Generator::getMock($originalClassName, $methods)

But you will lose all the expectation shortcuts like $this->once(). You will have to instantiate the expectations on your own:

$mock->expects(\PHPUnit_Framework_TestCase::once())

Look at the PHPUnit source code to see how the mocks are build




回答2:


If you build the mock outside the TestCase, it will not be accounted as a mock and it's expectations won't be checked automatically.

If your mock builder service is supposed to be used exclusively from PHPUnit tests (even if those tests are not related) you can have the testcase instance passed to the mock builder, so you can build the mock the usual way:

class MockBuilderService
{
    private $test;

    public function __construct(PHPUnit_Framework_TestCase $test)
    {
        $this->test = $test;
    }

    public function buildVeryComplexMock()
    {
        $mock = $this->test->getMock('MyClass');
        $mock->expects($this->test->once())
             ->method('foo')
             ->willReturn(1);      
        return $mock;      
    }
}

So you can use it from your test:

class ATest extends PHPUnit_Framework_TestCase
{
    public function testFoo()
    {
        $mock_builder = new MockBuilderService($this);
        $complex_mock = $mock_builder->buildVeryComplexMock($mock_configuration);

       // the mock expectations will be checked as usual
    }

}


来源:https://stackoverflow.com/questions/28566717/is-it-possible-to-create-a-mock-outside-a-test-case-in-phpunit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!