G
G
ganjo8882018-12-27 09:50:13
PHP
ganjo888, 2018-12-27 09:50:13

Am I writing phpunit tests correctly?

my method

public function getContent($query): ?string
    {
        if (isset($query) && !filter_var($query, FILTER_VALIDATE_URL)) {
            echo 'Некорректный Url';
        }
        $queryEncode = urlencode($query);
        if ($result = $this->loadFromCache($queryEncode)) {
            return $result['content'];
        }
        return null;
    }

Here is my test, I will be grateful for the corrections and assessment of my test, is it correct? Please correct me if this is not the case.
public function testGetContent()
    {
        $url = 'https://phpunit.de';

        $client = $this->createMock(Client::class);

        $contentService = new ContentService($client);
        $result = $contentService->getContent($url);

        $this->assertEquals(null, $result);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
index0h, 2018-12-27
@ganjo888

Generally speaking, at least 3 tests are needed to cover this method: when filter_var fails, result is cast to true and result is cast to false. Still missing a mock of the loadFromCache method, I don't see you covering its logic.
Checking for isset doesn't make sense. I would also add a type hint to the query. What will happen if closure is driven there?
Also, if something goes wrong - throw exceptions, you don’t need to smear yourself with this abomination of echo.
UPD
ganjo888 Here's some useful reading for you: https://github.com/index0h/php-conventions#7-test...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question