jjzjj

PHPUnit stub : default return value from map

coder 2024-04-17 原文

我在 PHPUnit 手册中读到,对于以下示例,方法调用 doSomething('a','b','c') 将返回 d方法调用 doSomething('e','f','g') 将返回 h

<?php
require_once 'SomeClass.php';

class StubTest extends PHPUnit_Framework_TestCase
{
    public function testReturnValueMapStub()
    {
        // Create a stub for the SomeClass class.
        $stub = $this->getMockBuilder('SomeClass')
                     ->getMock();

        // Create a map of arguments to return values.
        $map = array(
          array('a', 'b', 'c', 'd'),
          array('e', 'f', 'g', 'h')
        );

        // Configure the stub.
        $stub->method('doSomething')
             ->will($this->returnValueMap($map));

        // $stub->doSomething() returns different values depending on
        // the provided arguments.
        $this->assertEquals('d', $stub->doSomething('a', 'b', 'c'));
        $this->assertEquals('h', $stub->doSomething('e', 'f', 'g'));
    } 
}
?>

是否还有一种方法可以定义这样的返回值映射,但在特定输入参数没有特定返回值时使用默认返回值?

最佳答案

您可以使用 returnCallback 代替 returnValueMap,并重现值映射的作用:

<?php
require_once 'SomeClass.php';

class StubTest extends PHPUnit_Framework_TestCase
{
    public function testReturnValueMapStub()
    {
        // Create a stub for the SomeClass class.
        $stub = $this->getMockBuilder( 'SomeClass' )
            ->getMock();

        // Create a map of arguments to return values.
        $valueMap = array(
            array( 'a', 'b', 'c', 'd' ),
            array( 'e', 'f', 'g', 'h' )
        );

        $default = 'l';

        // Configure the stub.
        $stub->method( 'doSomething' )
            ->will( $this->returnCallback( function () use ( $valueMap, $default )
            {
                $arguments      = func_get_args();
                $parameterCount = count( $arguments );

                foreach( $valueMap as $map )
                {
                    if( !is_array( $map ) || $parameterCount != count( $map ) - 1 )
                    {
                        continue;
                    }

                    $return = array_pop( $map );
                    if( $arguments === $map )
                    {
                        return $return;
                    }
                }

                return $default;
            } ) );


        // $stub->doSomething() returns different values depending on
        // the provided arguments.
        $this->assertEquals( 'd', $stub->doSomething( 'a', 'b', 'c' ) );  
        $this->assertEquals( 'h', $stub->doSomething( 'e', 'f', 'g' ) );
        $this->assertEquals( 'l', $stub->doSomething( 'i', 'j', 'k' ) );
        $this->assertEquals( 'l', $stub->doSomething( 'any', 'arguments', 'at', 'all' ) );
    }
}

关于PHPUnit stub : default return value from map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31029390/

有关PHPUnit stub : default return value from map的更多相关文章

随机推荐