请考虑以下PHP代码
static public function IsLicenseValid($domain)
{
if (empty($domain)) {
throw new Exception;
}
$licenseResponse = Curl::Post(['hostname' => $domain]);
$Xml = new XML();
$xmlTree = $Xml->XMLToTree($licenseResponse);
if ($xmlTree['is_valid'] == 'true') {
return true;
}
}
return false;
}
我正在使用PHPUnit编写测试用例来检查上述方法。我能够涵盖所有情况,除了一个域许可证应该在true
xml节点中返回is_valid
的情况。
REST API非常安全,不接受来自白名单中未列出的IP的请求。如果有人通过非白名单IP发出请求,则API会为false
返回is_valid
值(这就是我覆盖false
的情况)
我知道这可以使用模拟对象完成,但我不确定如何编写一个模拟对象,可以覆盖域名有效的情况。有人可以帮忙吗?
提前致谢
答案 0 :(得分:1)
要测试此类,您将模拟Curl :: Post调用,但由于它是内联完成的,因此您需要使用依赖注入来使用模拟。
类别:
class ValidateLicense {
private $svc;
// Constructor Injection, pass the IntegratedService object here
public function __construct($Service = NULL)
{
if(! is_null($Service) )
{
if($Service instanceof LicenseAPI)
{
$this->SetService($Service);
}
}
}
function SetService(LicenseAPI $Service)
{
$this->svc = $Service
}
function ValidLicense($domain) {
$svc = $this->svc;
$result = $svc->IsLicenseValid($domain);
return $result;
}
}
class LicenseAPI {
public function IsLicenseValid($domain)
{
if( empty($domain)) {
throw new Exception;
}
$licenseResponse = Curl::Post(['hostname' => $domain]);
$Xml = new XML();
$xmlTree = $Xml->XMLToTree($licenseResponse);
if ($xmlTree['is_valid'] == 'true') {
return true;
}
return false;
}
}
测试:
class ValidateLicenseTest extends PHPUnit_Framework_TestCase
{
// Could also use dataProvider to send different returnValues, and then check with Asserts.
public function testValidLicense()
{
// Create a mock for the LicenseAPI class,
$MockService = $this->getMock('LicenseAPI', array('IsLicenseValid'));
// Set up the expectation for the return method
$MockService->expects($this->any())
->method('IsLicenseValid')
->will($this->returnValue(true));
// Create Test Object - Pass our Mock as the service
$TestClass = new ValidateLicense($MockService);
// Or
// $TestClass = new ValidateLicense();
// $TestClass->SetServices($MockService);
// Test
$domain = "localhost"; // Could be checked with the Mock functions
$this->assertTrue($TestClass->ValidLicense($domain));
}
// Could also use dataProvider to send different returnValues, and then check with Asserts.
public function testInValidLicense()
{
// Create a mock for the LicenseAPI class,
$MockService = $this->getMock('LicenseAPI', array('IsLicenseValid'));
// Set up the expectation for the return method
$MockService->expects($this->any())
->method('IsLicenseValid')
->will($this->returnValue(false));
// Create Test Object - Pass our Mock as the service
$TestClass = new ValidateLicense($MockService);
// Or
// $TestClass = new ValidateLicense();
// $TestClass->SetServices($MockService);
// Test
$domain = "localhost"; // Could be checked with the Mock functions
$this->assertFalse($TestClass->ValidLicense($domain));
}
}