Summer Sale! All accounts are 50% off this week.

catabozan's avatar

How to mock container resolved class with parameters?

I want to mock a class that is created using a static method

// this is how I instanciate the object
MyClass::from(AnotherClass $data);

// this is how the class looks like
class MyClass 
{
	 protected function __construct(AnotherClass $data)
	{
		// do stuff
	}

	 public static function from(AnotherClass $data): self
    {
        return new self($data);
    }
}

This is how I bind it to the container:

$this->app->bind(MyClass::class, function ($app, array $parameters) {
	return MyClass::from($parameters[0]);
});

This is how I use the class

$data = new AnotherClass()
app(MyClass::class, [$data])

I cannot store the $data globally to get rid of the parameter in my binding.

The problem is that when I try to mock or spy on MyClass it does not work.

$spy = spy(MyClass::class);
// ... do some stuff
$spy->shouldHaveReceived('reactPHPIdle');

If I dump app(MyClass::class) the mocked class is returned. But when I dump app(MyClass::class, [$data]) the original class is returned, not the mocked one.

How can I successfully mock my class? Is there a better way to do this (ex. refactor the class)?

0 likes
1 reply
martinbean's avatar
Level 80

@catabozan You could re-factor your class to be a factory if you’re given it a parameter and then expecting a new object to be instantiated and returned. That way you could then mock your factory class instead of having to deal with static methods.

1 like

Please or to participate in this conversation.