使用Codeception和Laravel 5模块进行单元测试的模拟类

时间:2018-06-27 13:51:34

标签: unit-testing laravel-5 mocking codeception

在单元测试中,这不起作用:

class SomeClassCest
{
    public function tryToTest(UnitTester $I)
    {
        $mock = Mockery::mock(MyClass::class);
        $mock->shouldReceive('action')->once()->andReturn(true);
        $I->haveInstance(MyClass::class, $mock);

        $classToTest = app(SomeClass::class);
        // this method calls the MyClass action method
        $classToTest->run();

        // some asserts here
    }
}

该模拟不会生效,$mock->action不会被调用,而是会调用真正的实现。如何使用Codeception和Laravel 5模块在单元测试中模拟类?

1 个答案:

答案 0 :(得分:0)

通常,在单元测试中,不会调用方法amOnRouteamOnPage,因此Laravel5->doRequest()将不会应用绑定,因此,为了在单元中模拟类Codeception套件的帮助程序:

class Unit extends \Codeception\Module
{

    /**
     * @param $realClass
     * @param $mock
     */
    public function mockClass($realClass, $mock)
    {
        $this->getModule('Laravel5')->getApplication()->instance($realClass, $mock);
    }

}

在单元测试中:

class SomeClassCest
{
    public function tryToTest(UnitTester $I)
    {
        $mock = Mockery::mock(MyClass::class);
        $mock->shouldReceive('action')->once()->andReturn(true);
        $I->mockClass(MyClass::class, $mock);

        $classToTest = app(SomeClass::class);
        // this method calls the MyClass action method
        $classToTest->run();

        // the mocked classs is used insetad of the real one

        // do some asserts here
    }
}