Reputation: 657
I have seen a few posts in various places about this and they all seem to have a similar answer. However for the life of me I cannot get the Mockery object working properly.
The Attribute model looks like this
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Attribute extends Model {
public function test()
{
return (new \App\Models\Value())->hello();
}
}
The Value model like this
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Value extends Model
{
public function hello()
{
return 'goodbye';
}
}
The PHPUnit test looks like this
use App\Models\Attribute;
class AttributeModelTest extends TestCase
{
public function testThing()
{
$mock = Mockery::mock('\App\Models\Value');
$mock->shouldReceive('hello')
->once()
->andReturn('hello');
$this->app->instance('\App\Models\Value', $mock);
$a = new \App\Models\Attribute();
$return = $a->test();
var_dump($return);
}
}
PHPUnit outputs 'goodbye', where I though that I am telling it to return 'hello' in the mock and it doesn't. Any ideas what I might be doing wrong?
Upvotes: 2
Views: 1930
Reputation: 23942
As discussed in comments:
Change return (new \App\Models\Value())->hello();
with return (\App::make('App\Models\Value'))->hello();
And in the test: $a = new \App\Models\Attribute();
with $a = App::make('App\Models\Attribute');
so Laravel will resolve the dependencies through the container
Upvotes: 1