neu*_*ert 5 php phpunit mocking
假设我想替换一个从数据库中获取数据库的对象中的方法,该数据库具有预先填充数据的数据库.我该怎么做?
根据https://phpunit.de/manual/current/en/test-doubles.html ...
可以在Mock Builder对象上调用setMethods(array $ methods)来指定要用可配置的测试double替换的方法.其他方法的行为不会改变.如果调用setMethods(NULL),则不会替换任何方法.
大.所以这告诉phpunit我想要替换哪些方法但是我在哪里告诉它我要用它替换它们?
我找到了这个例子:
protected function createSSHMock()
{
return $this->getMockBuilder('Net_SSH2')
->disableOriginalConstructor()
->setMethods(array('__destruct'))
->getMock();
}
Run Code Online (Sandbox Code Playgroud)
太棒了 - 所以这个__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));
}
}
Run Code Online (Sandbox Code Playgroud)
您的测试会模拟您尝试测试的确切类,这可能是一个错误,因为在模拟过程中可能会覆盖某些方法.
| 归档时间: |
|
| 查看次数: |
3315 次 |
| 最近记录: |