php - 如何用phpunit替换方法

标签 php mocking phpunit

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

根据 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/

相关文章:

database - 使用 phpUnit 进行 Laravel 5 测试而不重置我的数据库

PHPUnit 和 die 函数

php - 将数据从初始 XML 请求传递到后续页面

spring-mvc - Spring MockMVC、Spring 安全性和 Mockito

PHP - 使用 ==(相等)和 ===(相同)的意外行为

ruby-on-rails - 使用 Capybara Webkit 模拟 RSpec 功能规范中的外部 SSO 登录

python - 如何使用模拟作为函数参数在 Python 中修补常量

php - 确定将在 php 中发送的 http 状态

php - 迁移网站 - 在迁移过程中保持数据库同步

php - 依赖注入(inject)与静态