0

I am trying to run the unit test by using PHPUnit and Mock function. I am expecting an array as the result. But always getting an object and that is not related to the function which I called. How can I make this work?

Giving my code below

public function testGet()
{
    $mock = $this->createMock(Category::class);

    $map = [
        [1, 2],
        [3, 4],
    ];

    $mock->method('get')
        ->willReturn($this->returnValueMap($map));

    $testVal = $mock->get(1);
    echo '<pre>';
    print_r($testVal);
    die;
}

The result which I am getting from the print is,

PHPUnit\Framework\MockObject\Stub\ReturnValueMap Object
(
    [valueMap:PHPUnit\Framework\MockObject\Stub\ReturnValueMap:private] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => 2
                )

        [1] => Array
            (
                [0] => 3
                [1] => 4
            )

    )
)

I am expecting to get 2 if I pass 1 to the function and expecting to get 4 if I pass 3 to the function.

The function which I want to test is

public function get(int $id) { $categoryData = new CategoryData(); $fields = ['name', 'gid']; $getCat = $categoryData->get($id, $fields); if ($getCat) { return $getCat; } return []; }

Am I missing something here? Please help

1 Answer 1

1

Please try ->will( instead of ->willReturn(, so Phpunit does not return the map object (willReturn returns the argument verbatim) but further processes it.

Ref:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.