嘲笑不执行模拟方法
Mockery not executing mock method
我有 class 名称 Validator
并且它有一个方法 forVote
。
这是我的代码。
public function test_should_set_default()
{
$this->mock = \Mockery::mock(Validator::class);
$this->mock->shouldReceive('forVote')
->andReturnTrue();
$this->app->instance(Validator::class,$this->mock);
$factory = new Factory();
$this->assertTrue($factory->setDefault());
}
因此 Factory
调用 Processor
,后者又调用 Validator
。现在我想要模拟验证器 运行。但是它调用了真正的方法。
我做错了什么?
https://laravel.com/docs/5.6/container#introduction
since the repository is injected, we are able to easily swap it out
with another implementation. We are also able to easily "mock", or
create a dummy implementation of the UserRepository
when testing our
application.
我猜你目前可能正在像这样实例化你的依赖项:
$processor = new Processor()
和 $validator = Validator::make(...);
因此,为了使用你的模拟 class,你应该使用依赖注入,这意味着你的 classes 应该通过 __construct
方法注入你的依赖。
你的 Factory
class 应该是这样的:
class Factory {
$processor;
public function __construct(Processor $processor)
{
$this->processor = $processor;
}
public function setDefault()
{
$this->processor->callingValidator();
}
}
你的 Processor
应该是这样的:
class Processor {
$validator;
/**
* The Validator will resolve to your mocked class.
*
*/
public function __construct(Validator $validator)
{
$this->validator = $validator;
}
public function callingValidator()
{
$this->validator->make();
}
}
我有 class 名称 Validator
并且它有一个方法 forVote
。
这是我的代码。
public function test_should_set_default()
{
$this->mock = \Mockery::mock(Validator::class);
$this->mock->shouldReceive('forVote')
->andReturnTrue();
$this->app->instance(Validator::class,$this->mock);
$factory = new Factory();
$this->assertTrue($factory->setDefault());
}
因此 Factory
调用 Processor
,后者又调用 Validator
。现在我想要模拟验证器 运行。但是它调用了真正的方法。
我做错了什么?
https://laravel.com/docs/5.6/container#introduction
since the repository is injected, we are able to easily swap it out with another implementation. We are also able to easily "mock", or create a dummy implementation of the
UserRepository
when testing our application.
我猜你目前可能正在像这样实例化你的依赖项:
$processor = new Processor()
和 $validator = Validator::make(...);
因此,为了使用你的模拟 class,你应该使用依赖注入,这意味着你的 classes 应该通过 __construct
方法注入你的依赖。
你的 Factory
class 应该是这样的:
class Factory {
$processor;
public function __construct(Processor $processor)
{
$this->processor = $processor;
}
public function setDefault()
{
$this->processor->callingValidator();
}
}
你的 Processor
应该是这样的:
class Processor {
$validator;
/**
* The Validator will resolve to your mocked class.
*
*/
public function __construct(Validator $validator)
{
$this->validator = $validator;
}
public function callingValidator()
{
$this->validator->make();
}
}