在 Laravel 中使用 Mockery/phpUnit 时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37576867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error using Mockery/phpUnit in Laravel
提问by brianfr82
I'm a novice developer trying to get a test suite started for an existing laravel app but I have not experience in testing. Right now I'm just trying to get some tests built out to get some confidence and experience to write more substantial tests. I'm trying to test a relationship on a model(I realize it's not a very sensible tests) and trying to create a mocked model object to do so(I also understand it's better to do this in memory in a sqlite db but the major goal here is to test the controllers but I don't know how to deal with the authentication issue there). I have the following simple, stupid test:
我是一名新手开发人员,试图为现有的 Laravel 应用程序启动测试套件,但我没有测试经验。现在我只是想建立一些测试来获得一些信心和经验来编写更重要的测试。我正在尝试在模型上测试关系(我意识到这不是一个非常明智的测试)并尝试创建一个模拟模型对象来这样做(我也明白最好在 sqlite db 的内存中执行此操作,但主要这里的目标是测试控制器,但我不知道如何处理那里的身份验证问题)。我有以下简单而愚蠢的测试:
public function testFoo()
{
$lead = m::mock('Lead');
$this->mock->shouldReceive('program')->once();
$this->assertEquals($lead->program_id, $lead->program->id);
}
But I get the following error:
但我收到以下错误:
LeadTest::testFoo
BadMethodCallException: Received Mockery_0_Lead::getAttribute(), but no expectations were specified
I don't understand what this error is trying to tell me and I'm finding no help googling the issue or reading through the docs I can find.
我不明白这个错误试图告诉我什么,我找不到任何帮助来搜索问题或阅读我能找到的文档。
I assume I'm not setting the expected return values but this is a pretty general test and it doesn't seem right to hard code expected return values. What am I missing here?
我假设我没有设置预期的返回值,但这是一个非常通用的测试,硬编码预期的返回值似乎不正确。我在这里错过了什么?
I'm just testing a Laravel relationship to make sure I have things set up/implemented correctly:
我只是在测试 Laravel 关系,以确保我正确设置/实施了一些东西:
public function program()
{
return $this->belongsTo('Program');
}
回答by brianfr82
The problem was that I was missing the expected return value. It should've been something like this:
问题是我错过了预期的返回值。它应该是这样的:
$this->mock->shouldReceive('program')->once()->andReturn(someObjectOrValue);
And the assertion should've been something like:
断言应该是这样的:
$this->assertEquals(someObjectOrValue, $lead->program->id);
The Mockery docs are a lot more verbose than I originally thought. http://docs.mockery.io/en/latest/reference/expectations.html
Mockery 文档比我原先想象的要冗长得多。 http://docs.mockery.io/en/latest/reference/expectations.html