Reputation: 424
I have a class, and I'm trying to test one of it's methods but one of the methods calls a static method on the same class. I'm wondering how to test the first method without and stub the static method so that I'm only testing the first?
Here's a silly class as an example.
class MyEloquentModel extends Model
{
// Returns input concatenated with output of bar for that input
public function foo($input) {
$bar = MyEloquentModel::bar($input);
return $input." ".$bar;
}
// Returns world if input received is hello
public static function bar($input) {
if ($input == "hello") {
return "world";
}
}
}
Here's the test I've tried:
class MyEloquentModelTest extends TestCase
{
public function test_foo_method_returns_correct_value()
{
// Mock class
$mock = \Mockery::mock('App\MyEloquentModel');
$mock->shouldReceive('hello')
->once()
->with()
->andReturn('world');
// Create object
$my_eloquent_model = new MyEloquentModel;
$this->assertTrue($my_eloquent_model->foo('hello') == "hello world");
}
}
As it stands, the test returns "Could not load mock App\MyEloquentModel, class already exists"
Upvotes: 1
Views: 1377
Reputation: 1658
You can do it like this:
class MyEloquentModelTest extends TestCase
{
public function test_foo_method_returns_correct_value()
{
// Mock class
$my_mocked_eloquent_model = Mockery::mock('App\MyEloquentModel[bar]');
$my_mocked_eloquent_model->shouldReceive('bar')
->once()
->with('hello')
->andReturn('world');
$this->assertEquals("hello world", $my_mocked_eloquent_model->foo('hello'));
}
}
This created as partial mock for the MyEloquentModel class where only the method "bar" is mocked. In the shouldReceive
method the method you want to mock should be specified, not the argument for the method (as you have specified). It's instead for the with
method you should specify which arguments you expect will be supplied to the method.
The error you get "Could not load mock App\MyEloquentModel, class already exists" is most likely because you first specify a mock for the MyEloquentModel class and then try to create a new instance of the class using new MyEloquentModel;
. As you can see in my response you shouldn't create a new instance of the class but instead create a mock which you will use to call the method you want to test on.
Upvotes: 1