Home > Blockchain >  IOC container Or Mock in unit test
IOC container Or Mock in unit test

Time:09-17

hi i have written unit test and in my test suit i need related service about the unit test. i get the setup method like

    protected function setUp(): void
    {
        parent::setUp();
        $this->delayReportService = self::getContainer()->get(DelayReportService::class);
    }

in this test class i just want test a method that is not related to class dependencies so i mock all of its dependencies like this:

    protected function setUp(): void
    {
        parent::setUp();
        $this->delayReportService = new DelayReportService(
            $this->createMock(RedisQueueStorageClientInterface::class),
            $this->createMock(OrderRepository::class),
            $this->createMock(DelayReportRepository::class),
            $this->createMock(EstimatedArrivalTimeClientInterface::class),
            $this->createMock(ParameterBagInterface::class)
        );
    }

is this the best practice that when we don`t need dependencies in our test, we mock them? and in integration test we should not use mock right?

CodePudding user response:

is this the best practice that when we don`t need dependencies in our test, we mock them? and in integration test we should not use mock right?

In short, yes. Mocking services is fine and integration tests should not use mocks.

It depends on what you want to test. Both are fine, but the former is usually referred to as integration test and the latter as a unit test.

Looking at the services you inject, the latter can make more sense at least for things like the RedisQueueStorageClientInterface or your OrderRepository, because their actual implementations from the container will use the actual services, which requires you to have redis and database running for your test. You could also use alternative implementations for both in your test environment, e.g. store the data in memory as PHP arrays.

You can also use a mixed approach, i.e. fetch the other servics from the container, but not these ones. Similarly, you can use mocks for these services and actual implementations, which you instantiate yourself instead of fetching them from the container.

Both ways of testing have pros and cons, so there is no clear answer which you should prefer.

  • Related