【发布时间】:2013-06-19 06:12:28
【问题描述】:
我的班级中有一个非常基本的功能,完全按照评论所说的那样工作,如果此类中不存在子模型,它只会将调用转发给子模型。 这在我的测试中非常有效。
/**
* Handles calling methods on the user model directly from the provider
* Allows e.g. Guardian::User()->findOrFail(1) without having to redeclare
* the methods.
*
* @param $method
* @param $parameters
*
* @return mixed
*/
public function __call($method, $parameters){
$user = $this->createModel();
return call_user_func_array([$user, $method], $parameters);
}
但是我也想为此编写单元测试,在这种情况下我尝试编写的测试:
public function testProviderAsksModelToFind(){
$factoryUser = Factory::attributesFor('User', ['id' => 1]);
$p = m::mock('Webfox\Guardian\User\Guardian\Provider[createModel]',['']);
$user = m::mock('Webfox\Guardian\User\Guardian\User[find]');
$p->shouldReceive('createModel')->once()->andReturn($user);
$user->shouldReceive('find')->with(1)->once()->andReturn($factoryUser);
$this->assertSame($factoryUser, $p->find(1));
}
然而,这是吐出下面可爱的错误:
1) EloquentUserProviderTest::testProviderAsksModelToFind BadMethodCallException:方法 Webfox\Guardian\User\Guardian\Provider::find() 在此不存在 模拟对象
那么,我该如何解决这个问题才能让我的测试通过?
【问题讨论】:
-
专业提示:如果您在整个单元测试中都有静态范围解析运算符,那么您实际上并不是在编写单元测试;您正在编写集成测试。
-
测试魔术方法也可能是对单元测试的误解。单元通常依赖于接口,魔术方法可能与之相反。因此,您不能模拟它(和/或模拟它没有意义)。而是模拟和测试
__call。 -
@rdlowrey 我只看到工厂有静态。其他都还好,
标签: php phpunit laravel-4 magic-methods mockery