Laravel 的嘲弄不会嘲笑方法
Mockery with Laravel don't mocks a method
我使用 Laravel 5.5 并尝试模拟 class 的 public 方法,它在 class:
中使用
class ToTest {
public function filters() {
return 'original';
}
public function callMe() {
return $this->filters();
}
}
这是我的测试代码:
public function it_should_call_bla_bla()
{
$mock = $this->mock(ToTest::class);
$mock->shouldReceive('filters')->andReturn('not orignial');
$toTest = app(ToTest::class);
print_r($toTest->callMe());
}
private function mock($class)
{
$mock = Mockery::mock(app($class))->makePartial();
$this->app->instance($class, $mock);
return $mock;
}
$toTest->callMe()
returns original
...
问题是,你用一个对象而不是 class 创建你的模拟,正确的代码,以满足你的要求是这样的:
$mock = Mockery::mock($class)->makePartial();
原来你在嘲笑对象。当 ToTest
对象已经初始化时,mocking 只覆盖了 filters
方法,而 callMe
完好无损。如果您尝试使用旧代码转储 print_r($toTest->filters());
,它将 return "not original"
。
我使用 Laravel 5.5 并尝试模拟 class 的 public 方法,它在 class:
中使用class ToTest {
public function filters() {
return 'original';
}
public function callMe() {
return $this->filters();
}
}
这是我的测试代码:
public function it_should_call_bla_bla()
{
$mock = $this->mock(ToTest::class);
$mock->shouldReceive('filters')->andReturn('not orignial');
$toTest = app(ToTest::class);
print_r($toTest->callMe());
}
private function mock($class)
{
$mock = Mockery::mock(app($class))->makePartial();
$this->app->instance($class, $mock);
return $mock;
}
$toTest->callMe()
returns original
...
问题是,你用一个对象而不是 class 创建你的模拟,正确的代码,以满足你的要求是这样的:
$mock = Mockery::mock($class)->makePartial();
原来你在嘲笑对象。当 ToTest
对象已经初始化时,mocking 只覆盖了 filters
方法,而 callMe
完好无损。如果您尝试使用旧代码转储 print_r($toTest->filters());
,它将 return "not original"
。