how to pass object to test method in laravel?

Viewed 449

I have a class with the following signature:

class Service
{
    public function __construct(
        Class $a,
        Class $b,
        Class $c
    ) 

how can I get an instance of it in a test method? the call through the constructor throws the following error

Too few arguments to function Service::__construct(), 0 passed 

but in the application itself, this class works, for example, in the command:

class ServiceCommand extends AbstractCommand
{
    protected $service;


    public function __construct(Service $service)
    {
        parent::__construct();
        $this->service = $service;
    }

How to get an instance of the Service object in a phpunit test-method?

1 Answers

but in the application itself, this class works

You need to understand Dependency injection and how the Service container works in Laravel.

How to get an instance of the Service object in a phpunit test-method

Two ways - one for feature testing, one for unit:

Feature

Use the service container to inject dependencies.

$this->service = $this-app->make(Service::class);

Unit

Mock your dependencies - read more about mocking

$mockA = $this->createMock(Class::class);
// ...
$this->service = new Service($mockA...);
Related