我开始在Laravel 4中进行单元测试,并且在我添加到标准User模型的模型中卡住测试自定义方法。phpunit找不到模型方法(Laravel/Mockery)
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends BaseModel implements UserInterface, RemindableInterface {
/**
* Logs to the database and streams an update
* Uses logIt and streamIt on Base model
* @param String $action The action being performed
* @return void
*/
private function logAndStream($action)
{
$this->logIt('info', $action.'d user '.$this->username);
$this->streamIt($action.'d user '.$this->username);
}
此类扩展这又延伸口才的BaseModel,并具有定义Logit模型和StreamIt方法,像这样:
class BaseModel extends Eloquent {
/**
* Log an action to log file
* @return void
*/
protected function logIt($level, $msg) {
...
}
/**
* Log an action to activity stream
* @return void
*/
protected function streamIt($msg, $client = null, $project = null) {
...
}
所有这些代码工作正常,当我手动测试的东西。但是现在我想创建一个单元测试来自动化它。
class UserTest extends TestCase {
public function testLogAndStream()
{
$base = Mockery::mock('BaseModel')->shouldAllowMockingProtectedMethods();
$base->shouldReceive('logIt')
->with('info', 'Created user Tester')
->once();
$user = new User;
$user->username = 'Tester';
$user->logAndStream('Create');
}
当我尝试运行这个,我得到一个失败抱怨找不到logAndStream。
1) UserTest::testLogAndStream
BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::logAndStream()
我错过了什么?
大 - 非常感谢你。将logAndStream更改为public允许测试现在按预期访问它。你会如何建议测试logIt和streamIt在同一个User对象上调用(因为sholdReceive不适用于Models)? – Fixspec
我从来没有在模拟模型上使用'shouldReceive'出现问题。我将编辑答案以添加一个简短的片段。 – Kryten
非常感谢。我现在已经弄糊涂了,会发布最终代码。顺便说一句,我参考shouldReceive是(真正的)雄辩模型,而不是嘲笑模型。我不认为我可以从真实数据库中抽出一些东西并测试shouldReceive。如果有办法做到这一点,那么我有兴趣学习。 – Fixspec