在单元测试中,这不起作用:
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模块在单元测试中模拟类?
答案 0 :(得分:0)
通常,在单元测试中,不会调用方法amOnRoute
,amOnPage
,因此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
}
}