Phpunit call native function once and return stdClass

Asked

Viewed 43 times

0

github.com/Hubtodo/traits/blob/master/tests/Jsonrendertest. p hp I’m doing a successful test of my trait function

My trait is this:

<?php

namespace HubToDo\Traits;

use InvalidArgumentException;

/**
 * Trait JsonRender.
 *
 * @package HubToDo\Traits
 */
trait JsonRender
{
    /**
     * Wrapper for json_decode that throws when an error occurs.
     *
     * @param string $json    JSON data to parse
     * @param bool $assoc     When true, returned objects will be converted
     *                        into associative arrays.
     * @param int    $depth   User specified recursion depth.
     * @param int    $options Bitmask of JSON decode options.
     *
     * @return mixed
     * @throws InvalidArgumentException if the JSON cannot be decoded.
     * @link http://www.php.net/manual/en/function.json-decode.php
     */
    function jsonDecode($json, $assoc = false, $depth = 512, $options = 0)
    {
        $data = json_decode($json, $assoc, $depth, $options);

        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new InvalidArgumentException('json_decode error: ' . json_last_error_msg());
        }

        return $data;
    }
}

And that’s my test:

<?php

namespace HubToDo\Traits\Tests;

use HubToDo\Traits\JsonRender;
use PHPUnit_Framework_TestCase;

/**
 * Class JsonRenderTests.
 *
 * @package HubToDo\Traits\Tests
 */
class JsonRenderTest extends PHPUnit_Framework_TestCase
{
    public function testJsonDecodeSuccess()
    {
        $json = '{"b2w": {"main": null, "show": "CARREGADORES", "categories": {"familyId": 4, "categoryId": 18, "subFamilyId": 1, "subCategoryId": 2577}}}';
        $json_render = $this->getMockForTrait(JsonRender::class);

        // call function json_decode once and value \stdClass
//        $json_render->method('json_decode')
//            ->with($json)
//            ->will($this->returnValue(\stdClass::class));

        $this->assertInstanceOf(\stdClass::class, $json_render->jsonDecode($json));
    }
}

However, I would like the test to verify that: The json_decode function is called only once Passing the variable $ json And returning a stdClass.

I believe that in this way my function would be fully covered, or do you find it totally unnecessary?

  • Well, I don’t quite understand what your question is. But in the I believe that way my function would be fully covered its code is not fully covered, and Exception?

  • https://github.com/HubToDo/traits/blob/master/tests/JsonRenderTest.php&#Xa I opened this question because I would believe it to be the right thing to do.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.