【发布时间】:2010-11-19 00:51:02
【问题描述】:
我已经搜索过,但找不到我正在寻找的内容,并且手册在这方面没有太大帮助。我对单元测试相当陌生,所以不确定我是否走在正确的轨道上。无论如何,关于这个问题。我有一堂课:
<?php
class testClass {
public function doSomething($array_of_stuff) {
return AnotherClass::returnRandomElement($array_of_stuff);
}
}
?>
现在,显然我希望 AnotherClass::returnRandomElement($array_of_stuff); 每次都返回相同的内容。我的问题是,在我的单元测试中,如何模拟这个对象?
我尝试将AnotherClass 添加到测试文件的顶部,但是当我想测试AnotherClass 时,我收到“无法重新声明类”错误。
我想我了解工厂类,但我不确定在这种情况下如何应用它。我是否需要编写一个完全独立的包含测试数据的 AnotherClass 类,然后使用 Factory 类而不是真正的 AnotherClass 来加载它?或者使用工厂模式只是一个红鲱鱼。
我试过这个:
$RedirectUtils_stub = $this->getMockForAbstractClass('RedirectUtils');
$o1 = new stdClass();
$o1->id = 2;
$o1->test_id = 2;
$o1->weight = 60;
$o1->data = "http://www.google.com/?ffdfd=fdfdfdfd?route=1";
$RedirectUtils_stub->expects($this->any())
->method('chooseRandomRoot')
->will($this->returnValue($o1));
$RedirectUtils_stub->expects($this->any())
->method('decodeQueryString')
->will($this->returnValue(array()));
在 setUp() 函数中,但这些存根被忽略,我无法确定这是我做错了什么,还是我访问 AnotherClass 方法的方式。
帮助!这让我发疯了。
【问题讨论】:
标签: php unit-testing mocking phpunit