gpt4 book ai didi

php - 如何用phpunit替换方法

转载 作者:可可西里 更新时间:2023-11-01 13:54:00 25 4
gpt4 key购买 nike

假设我想用一个预先填充数据的方法替换一个从数据库获取数据库的对象中的方法。我该怎么做?

根据 https://phpunit.de/manual/current/en/test-doubles.html ...

setMethods(array $methods) can be called on the Mock Builder object to specify the methods that are to be replaced with a configurable test double. The behavior of the other methods is not changed. If you call setMethods(NULL), then no methods will be replaced.

太棒了。所以这告诉 phpunit 我想替换哪些方法,但我在哪里告诉它我要用什么替换它们?

我找到了这个例子:

protected function createSSHMock()
{
return $this->getMockBuilder('Net_SSH2')
->disableOriginalConstructor()
->setMethods(array('__destruct'))
->getMock();
}

太好了 - 所以 __destruct 方法被替换了。但是它被什么取代了呢?我不知道。这是它的来源:

https://github.com/phpseclib/phpseclib/blob/master/tests/Unit/Net/SSH2Test.php

最佳答案

使用不执行任何操作的方法,但您可以稍后配置其行为。尽管我不确定您是否完全理解模拟的工作原理。你不应该模拟你正在测试的类,你应该模拟被测试类所依赖的对象。例如:

// class I want to test
class TaxCalculator
{
public function calculateSalesTax(Product $product)
{
$price = $product->getPrice();
return $price / 5; // whatever calculation
}
}

// class I need to mock for testing purposes
class Product
{
public function getPrice()
{
// connect to the database, read the product and return the price
}
}

// test
class TaxCalculatorTest extends \PHPUnit_Framework_TestCase
{
public function testCalculateSalesTax()
{
// since I want to test the logic inside the calculateSalesTax method
// I mock a product and configure the methods to return some predefined
// values that will allow me to check that everything is okay
$mock = $this->getMock('Product');
$mock->method('getPrice')
->willReturn(10);

$taxCalculator = new TaxCalculator();

$this->assertEquals(2, $taxCalculator->calculateSalesTax($mock));
}
}

您的测试模拟了您要测试的确切类,这可能是一个错误,因为某些方法可能在模拟过程中被覆盖。

关于php - 如何用phpunit替换方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26737767/

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