Vaweto's avatar
Level 18

Unknown named parameter error when test a class

I have a class that use a service on constructor like above:

public function __construct(private $test, private User $user)
{
    $this->service = new service(
        user: $this->user,
        test: $this->test,
    );
}

When i try to test the class and mock the service i get Error : Unknown named parameter $user.

Did anyone has see that again?

0 likes
2 replies
LaryAI's avatar
Level 58

The error "Unknown named parameter $user" occurs because you are trying to mock the service in your test, but the constructor of the class being tested has named parameters. To resolve this issue, you can use the getMockBuilder method from PHPUnit to create a mock object of the service and pass it as an argument to the constructor.

Here's an example of how you can modify your test to mock the service:

use PHPUnit\Framework\TestCase;

class YourTestClassTest extends TestCase
{
    public function testYourMethod()
    {
        // Create a mock object of the service
        $serviceMock = $this->getMockBuilder(Service::class)
            ->disableOriginalConstructor()
            ->getMock();

        // Create an instance of the class being tested, passing the mock service as an argument
        $yourClass = new YourClass($serviceMock);

        // Perform your test assertions
        // ...
    }
}

Make sure to replace Service with the actual class name of your service. This way, you can mock the service and pass it as an argument to the constructor without encountering the "Unknown named parameter" error.

Please or to participate in this conversation.