Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dependency injection not working during tests #76

Open
Spartaques opened this issue Jan 4, 2022 · 2 comments
Open

Dependency injection not working during tests #76

Spartaques opened this issue Jan 4, 2022 · 2 comments

Comments

@Spartaques
Copy link

Hello guys. I have a controller called UserController. And i have a UserService that call getById method that returns some object. How can i mock this call when i test UserController?

I tries this code
` /** @var \Hyperf\Di\Container $c */
$c = \Hyperf\Utils\ApplicationContext::getContainer();

    $queryServiceMock = $this->createMock(QueryService::class);

    $queryServiceMock->method('appByKeyAndDomain')->willReturn((object)[
        'id' => 1,
        'key' => 'test',
        'timezone' => 'UTC'
    ]);

    $c->set(QueryService::class, $queryServiceMock);

    \Hyperf\Utils\ApplicationContext::setContainer($c);`

but it would not work.

@Spartaques
Copy link
Author

So, i have not found a way to bound some implementation to serviceContainer during testing. It's strange for me.

@Castrozan
Copy link

So you're trying to unit test a controller class with dependency injections using Inject DI and mocking some dependency, that's right?

I was looking for this last week and found on php-di documentation that it is within best practices not to unit-test controllers that way.

Not sure if it's the right way of doing this, but i found a work around by reflecting the dependency propriety and setting its value to a mocked version of it.

It looks like this.

        $controller = new UserController();
        $queryServiceMock  = $this->createMock(QueryService::class);

        $queryServiceMock->method('appByKeyAndDomain')->willReturn((object)[
            'id' => 1,
            'key' => 'test',
            'timezone' => 'UTC'
        ]);

        $reflectedController = new \ReflectionClass('App\Controller\UserController');
        $dependency = $reflectedController->getProperty('queryService');
        $dependency->setAccessible(true);
        $dependency->setValue($controller, $queryServiceMock);

        $this->asserTrue(true);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants