Answer the question
In order to leave comments, you need to log in
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;
}
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
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 questionAsk a Question
731 491 924 answers to any question