PHPUnit存根:来自map的默认返回值
发布时间:2020-12-13 16:57:03 所属栏目:PHP教程 来源:网络整理
导读:我已经阅读了 PHPUnit手册,通过以下示例,方法调用doSomething(‘a’,’b’,’c’)将返回d并且方法调用doSomething(‘e’,’f’,’g’ )将返回h. ?phprequire_once 'SomeClass.php';class StubTest extends PHPUnit_Framework_TestCase{ public function test
我已经阅读了
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','c')); $this->assertEquals('h',$stub->doSomething('e','g')); } } ?> 是否还有一种方法可以定义这样的返回值映射,但是当特定输入参数没有特定的返回值时,使用默认返回值? 解决方法
您可以使用returnCallback而不是returnValueMap,并重现值map正在执行的操作:
<?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','d' ),array( 'e','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','c' ) ); $this->assertEquals( 'h',$stub->doSomething( 'e','g' ) ); $this->assertEquals( 'l',$stub->doSomething( 'i','j','k' ) ); $this->assertEquals( 'l',$stub->doSomething( 'any','arguments','at','all' ) ); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |