Answer the question
In order to leave comments, you need to log in
How to write phpunit tests correctly?
I am learning to write phpunit tests, I want to try to write a test of
my code on the existing code
<?php
class ContentService implements ContentServiceInterface
{
private $client;
/**
* ContentServiceInterface constructor.
* @param Client $client
*/
public function __construct(Client $client)
{
$this->client = $client;
}
/**
* @param $query
* @return mixed
*/
public function getContent($query): ?string
{
$queryEncode = urlencode($query);
if ($result = $this->loadFromCache($queryEncode)) {
return $result['content'];
}
return null;
}
public function sqrt($x)
{
return sqrt($x);
}
}
<?php
namespace Tests\Feature;
use App\Services\ContentService;
use GuzzleHttp\Client;
use Tests\TestCase;
class ContentServiceTest extends TestCase
{
public $client;
public function __construct()
{
parent:: __construct();
}
public function testsqrt($client): void
{
$o = new ContentService($client);
$this->assertEquals(4, $o->sqrt(16));
}
}
ArgumentCountError: Too few arguments to function Tests\Feature\ContentServiceTest::testsqrt(), 0 passed
Answer the question
In order to leave comments, you need to log in
Correct test for this code:
<?php
namespace Tests\Feature;
use App\Services\ContentService;
use GuzzleHttp\Client;
use Tests\TestCase;
class ContentServiceTest extends TestCase
{
public function testSqrt(): void
{
$client = new Client();
$o = new ContentService($client);
$this->assertEquals(4, $o->sqrt(16));
}
}
<?php
namespace Tests\Feature;
use App\Services\ContentService;
use GuzzleHttp\Client;
use Tests\TestCase;
/**
* @coversDefaultClass \App\Services\ContentService
*/
class ContentServiceTest extends TestCase
{
/**
* @covers ::sqrt
*/
public function testSqrt(): void
{
$client = new Client();
$o = new ContentService($client);
$this->assertEquals(4, $o->sqrt(16));
}
}
well, as it were
and that says it all)
who will inject the client into the test for you?public function testsqrt($client): void
<?php
namespace Tests\Feature;
use App\Services\ContentService;
use GuzzleHttp\Client;
use Tests\TestCase;
class ContentServiceTest extends TestCase
{
public function testsqrt(): void
{
$config = [];
$client = new GuzzleHttp\Client($config);
$o = new ContentService($client);
$this->assertEquals(4, $o->sqrt(16));
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question