【发布时间】:2018-07-31 10:32:06
【问题描述】:
究竟如何为使用实时数据库的方法编写测试?
考虑这段代码:
class PricingRepository extends GenericRepository
{
public function getOptionPrice(int $productId, int $quantity, float $productPrice = 0.0): float
{
//retrieves option record for a given product
$row = $this->getMySql()->paramQuery("
select * from pricing
where product_id = ?", array(
$productId
))->getSingleArray();
//based on pricing type computes appropriate value
if ($row['pricing_type'] === 'Quantity-based')
return $row['base'] + $row['amount_per_quantity'] * $quantity;
if ($row['pricing_type'] === 'Percentage-based')
return $productPrice * $row['percentage'];
throw new \InvalidArgumentException("invalid pricing type detected");
}
}
我有很多类似上面的方法,所以我想确保我的测试是可靠的,并且不会随着数据库数据的变化而改变。我正在寻找针对一流单元测试方法的建议/解决方案,并且可能不依赖于数据库中数据的更改。
我现在可以编写一个简单的单元测试的方式可能是这样的:
use PHPUnit\Framework\TestCase;
class OptionPricingTest extends TestCase
{
function setUp()
{
$this->pricingRepository = new PricingRepository();
}
function testOptionPricing()
{
$actual_option_price = $this->pricingRepository->getOptionPrice(111, 1, 100);
$this->assertEquals(10.0, $actual_option_price);
}
}
但如果数据或定价类型发生变化,我的测试也必须改变。
【问题讨论】:
标签: php unit-testing phpunit php-7