Home > OS >  How to test this without mocks?
How to test this without mocks?

Time:11-20

I've been reading about testing without mocks and in general I like it. However, I've been struggling what to do when there's some third-party class included. For example if we have this class:

<?php

use External\ThirdPartyService;
use External\ThirdPartyException;

class AdapterForExternalService implements OurInterface
{
    private ThirdPartyService $external;

    public function __construct(ThirdPartyService $external)
    {
        $this->external = $external;
    }

    public function something(): int
    {
        try {
            return $this->external->someMethod();
        } catch (ThirdPartyException $e) {
            return 1;
        }
    }
}

I know how to test it by mocking the external class, but is it possible to do it without mocking too?

If mocking is non-avoidable here, what if the ThirdPartyService class is final?

CodePudding user response:

The something() method is not changing observable state. It only wraps the call to the third party service and turns the exception into an integer return value. The thing that is observable and that you could (in theory) assert on, is the call to the service and the returned results. This means, if you are not mocking, you will have to call that service.

To test this at all, you have to mock the dependency. If that class is really final, you can create a non-final facade for it and mock that.

  • Related