数据提供的最佳实践-PHPUnit [英] Best Practices for Data Providing - PHPUnit
问题描述
我目前正在为一个库编写单元测试,在从数据中重构业务逻辑之后,我对现在如何测试逻辑有些困惑!
I'm currently writing units tests for a library, after refactoring business logic from the data, I'm now in a bit of confused state over how to now test the logic!
例如,我有一个相当复杂的过程,要传递一组数据,我将为此使用数据提供程序,以便确保它可以在各种情况下使用.
For example, I have a quite complex process which an array of data get's passed through, I'm going to use a data provider for this so I can make sure it will work for all sorts of cases.
有了要通过数据提供者传递的数据,我是否也应该传递预期的结果?还是应该在测试中计算出来.
With the data that I'm going to be passing in through the data provider, should I also be passing an expected outcome? Or should this be calculated in the test.
如前所述,计算过程是一个非常复杂的过程,而不是$a + $b
.
As said, the process for the calculating is quite a complicated process, not quite $a + $b
.
推荐答案
对于数据提供程序,我还提供了预期的结果.因为我希望该方法接受输入并返回一个值,所以我不想重复执行计算,因为其中一种实现可能有错误.
With data providers, I also provide the expected result. As I want the method to take the inputs and return a value, I do not want to implement the calculation twice, as 1 of the implementations may have an error.
由于我实际上正在测试有问题的方法/功能,因此我不打算使用模拟程序.
I am not looking to use a mock since I am actually testing the methods/functions in question.
如果我们基于4个参数进行计算,那么我的数据提供者将传递5.第一个参数是预期结果,然后是要传递给方法/函数的参数.
If we are calculating something based on 4 parameters, then my data provider will pass 5. The first parameter is the expected result, followed by the parameters to be passed to the method/function.
由此,我的电话非常简单:
From this, my call is pretty straight forward:
public static function GetRemoteAddressFromWebServerDataProvider()
{
return array(
array('127.0.0.1', NULL, '127.0.0.1'),
array('127.0.0.1', '127.0.0.1', NULL),
);
}
/**
* @dataProvider GetRemoteAddressFromWebServerDataProvider
*/
public function testGetRemoteAddressFromWebServer($Result, $HTTPXSetting, $RemoteAddress)
{
$_SERVER['HTTP_X_FORWARDED_FOR'] = $HTTPXSetting;
$_SERVER['REMOTE_ADDR'] = $RemoteAddress;
$this->assertEquals($Result, GetRemoteAddressFromWebServer());
}
这篇关于数据提供的最佳实践-PHPUnit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!