PHP - 简单 - 列出模拟对象的方法的每个呼叫
-
13-12-2019 - |
题
我的问题是,我需要列出每个调用模拟对象,因为我需要检查它们。我在简单的文档中没有找到关于此功能的任何内容。:s
也许有另一种方法来测试我的代码:
class Clean_Collection_Tree_NestedArrayParser {
protected $path = array();
protected $depth = -1;
/** @var Clean_Collection_Tree_MapTreeInterface */
protected $tree;
public function setBasePath(array $path) {
$this->path = $path;
}
public function setTree(Clean_Collection_Tree_MapTreeInterface $tree) {
$this->tree = $tree;
}
public function parse($subject) {
$this->parseArray($subject);
}
public function parseArray(array $array) {
++$this->depth;
foreach ($array as $key => $value) {
$this->path[$this->depth] = $key;
if (is_array($value)) {
$this->tree->put($this->path, new Clean_Collection_Map_Map());
$this->parseArray($value);
} else
$this->tree->put($this->path, $value);
}
if (!empty($array))
array_pop($this->path);
--$this->depth;
}
}
.
这是一个等待嵌套数组的解析器,我打算创建一个地图对象树。我用 setTree(clean_collection_tree_maptreeface $树)注入实际树)和地图树界面是:
interface Clean_Collection_Tree_MapTreeInterface extends Clean_Collection_CollectionInterface {
public function putAll(array $array);
public function put(array $path, $value);
public function get(array $path);
public function getAll(array $pathes);
public function removeAll(array $pathes);
public function remove(array $path);
public function contains(array $path);
}
.
解析器仅使用 put(数组$ path,$ value)方法。所以列出了每个被叫的Put方法会告诉我解析器出现了出现问题。(如果simpleemock没有此功能,我可以创建自己的模拟对象,我们实现接口。我在它。)
解决方案
问题在于SimpleMock类设计:
protected function addCall($method, $args) {
if (! isset($this->call_counts[$method])) {
$this->call_counts[$method] = 0;
}
$this->call_counts[$method]++;
}
.
它们应该为日志记录呼叫属性创建了一个记录器类,而不是在simplemock中设置属性...我们可以通过扩展simplemock类来创建一个解决方法:
class LoggedMock extends SimpleMock {
protected $invokes = array();
public function &invoke($method, $args) {
$this->invokes[] = array($method, $args);
return parent::invoke($method, $args);
}
public function getMockInvokes() {
return $this->invokes;
}
}
.
并将其设置为基础模拟类:
require_once __DIR__.'simpletest/autorun.php';
SimpleTest::setMockBaseClass('LoggedMock');
.
之后,我们可以使用 $ mockobj-> getmockinvokes()。
编辑:我们无法扩展addcall,因为在调用方法的第一行中,方法名称被转换为小写,所以通过扩展addcall,我们只能记录小写格式,而不是骆驼箱。(我认为小写转换是一个错误......)
我为演示创建了测试:
interface Nike {
public function justDoIt();
}
class NikeUser {
protected $nike;
public function setNike(Nike $nike) {
$this->nike = $nike;
}
public function doIt() {
$this->nike->justDoIt();
}
}
Mock::generate('Nike', 'MockNike');
class NikeUserTest extends UnitTestCase {
public function testDoItButWeDontWantJustDoIt() {
$mockNike = new MockNike();
$nikeUser = new NikeUser();
$nikeUser->setNike($mockNike);
$expectedInvokes = array();
$nikeUser->doIt();
$expectedInvokes[] = array('justDoIt', array());
$this->assertEqual($expectedInvokes, $mockNike->getMockInvokes());
}
}
. 不隶属于 StackOverflow