gpt4 book ai didi

php - 在 PHP 单元中创建模拟对象

转载 作者:可可西里 更新时间:2023-11-01 12:18:47 24 4
gpt4 key购买 nike

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

<?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() 函数中,但是这些 stub 被忽略了,我无法确定是我做错了什么,还是我访问 AnotherClass 方法的方式。

帮助!这让我抓狂。

最佳答案

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

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,然后重新创建它,以便它只包含返回测试数据的函数。不过,通常情况下,您并不想真正从程序中删除类,这就是为什么要像上面的示例一样传递类。

关于php - 在 PHP 单元中创建模拟对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1267344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com