简体   繁体   中英

PHPUnit: how test the __() php

I have this exception:

throw  new \DomainException(__("message d'erreur"));

I don't know how can I do the test of this instruction by PHPUnit: __() .

Im sure there are other ways which i'm not aware of but I would do it like the following, if you downvote please comment why. If I learn something new I'm happy.


Ok, depending on whether the application expects the function to be defined to work or whether its expected but not part of the current test you could mock it:

Using: php-mock/php-mock-phpunit

<?php
use PHPUnit\Framework\TestCase;

class SomeTest extends TestCase
{
    use \phpmock\phpunit\PHPMock;

    /**
     * __() function must exist or test fails.
     */
    public function testDoubleUndescoreFunction()
    {
        $this->assertTrue(function_exists('__'), '__() function does not exist');
    }

    // or

    /**
     * __() function will be mocked.
     */
    public function testDoubleUndescoreFunction()
    {
        // mock __() function
        if (!function_exists('__')) {
            $mocks['__'] = $this->getFunctionMock(__NAMESPACE__, "__");
            $mocks['__']->expects($this->any())->willReturnCallback(
                function ($value) {
                    $this->assertInternalType('string', $value);
                    return $value;
                }
            );
        }

        // test
        $this->assertTrue(function_exists('__'), '__() function does not exist');    

        try {
            //
            // run test which will cause the exception

        } catch (\Exception $e) {
            $this->assertInstanceOf('DomainException', $e);
            $this->assertEquals('message d\'erreur', $e->getMessage());
        }
    }
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM