samedi 23 novembre 2019

Unit testing a function with a timestamp

I have an object function to send news to an API:

class Manager
{
    public function __construct(GuzzleHttp\Client $client)
    {
        $this->client = $client;
    }


    public function uploadNews($title, $text, $timestamp = null)
    {
        // DEFAULT FOR PUBLISH TIMESTAMP IS SET IF VALUE IS NULL
        $timestamp = $timestamp ?? time();

        $requestBody = [
            'header' => [
                'Accept' => 'application/json',
            ],
            'timeout' => 300,
            'body' => [
                'title' => $title,
                'text' => $text,
                'publish_date' => $timestamp,
            ]
        ];

        return $this->client->request('POST', 'http://api/endpoint', $requestBody);
    }
}

How do I write a PHPUnit unit test to test the final $request passed to the client's request() function is of the expected format, when the $timestamp is not set (the API expects a timestamp)? I've written a unit test. But is not ideal, since there could be a difference in the tow timestamps.

class ManagerTest extends \PHPUnit\Framework\TestCase
{
    public function testCanUploadNewsWithoutTimestamp()
    {
        $expectedRequestBody = [
            'header' => [
                'Accept' => 'application/json',
            ],
            'timeout' => 300,
            'body' => [
                'title' => 'News title',
                'text' => 'News article sample text.',
                'publish_date' => time(),
            ]
        ];

        $guzzleMock = $this->createMock(GuzzleHttp\Client::class);
        $guzzleMock->expects($this->once())
            ->method('request')
            ->with(
                'POST',
                'http://api/endpoint',
                $expectedRequestBody
            );

        (new Manager($guzzleMock))->uploadNews(
            'News title',
            'News article sample text.'
        );
    }
}

This is my current test result:

Parameter 2 for invocation GuzzleHttp\Client::request('POST', 'http://api/endpoint', Array (...)) does not match expected value.
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
     'body' => Array (
         'title' => 'News title'
         'text' => 'News article sample text.'
-        'publish_date' => 1574550178
+        'publish_date' => 1574550179
     )
 )

PS: I'm really new to Test Driven Development, so the answer might be obvious and I might still not know it.

Aucun commentaire:

Enregistrer un commentaire