9

我已经搜索过,但找不到我要找的东西,并且手册在这方面没有太大帮助。我对单元测试还很陌生,所以不确定我是否走在正确的轨道上。无论如何,关于这个问题。我有一堂课:

<?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方式。

帮助!这让我发疯了。

4

1 回答 1

6

使用单元测试,您希望创建包含静态数据的“测试”类,然后将它们传递给您的测试类。这会从测试中删除变量。

class Factory{
    function build()
    {
        $reader = new reader();
        $test = new test($reader);
        // ..... do stuff
    }

}

class Factory{
    function build()
    {
        $reader = new reader_mock();
        $test = new test($reader);
        // ..... do stuff
    }

}
class reader_mock
{
    function doStuff()
    {
        return true;
    }
}

因为您使用的是静态类,所以您必须AnotherClass从程序中删除,然后重新创建它,以便它只包含返回测试数据的函数。不过,通常情况下,您并不想真正从程序中删除类,这就是为什么您要像上面的示例一样传递类。

于 2009-08-12T16:46:28.723 回答