我从一个API中获得了一个JSON结构,并且需要检查成功响应是否有两个具有特定值的特定属性。
关键问题:
成功响应实例:
{
'success': true,
'user_ip': '212.20.30.40',
'id': '7629428643'
}
肮脏的解决办法是
<?php
public function testAddAccount() {
$response = $this->api->addAccount( '7629428643' );
$this->assertTrue(
$response->success === TRUE &&
$response->id === '7629428643'
);
}
但我认为必须有更好和更清洁的解决办法,是吗?
发布于 2012-08-21 07:40:35
您希望对要验证的每个属性使用assertEquals()
。虽然您通常只想在每个测试用例中测试一件东西,但有时需要多个断言来测试“一件事”。因此,多个断言是可以的。
您还可能希望断言属性存在于$response
对象中,以避免通知。有关示例,请参见以下内容:
public function testAddAccount() {
// Attempt to create an account.
$response = $this->api->addAccount('7629428643');
// Verify that the expected properties are present in the response.
$this->assertObjectHasAttribute('success', $response);
$this->assertObjectHasAttribute('id', $response);
// Verify the values of the properties.
$this->assertEquals(true, $response->success);
$this->assertEquals('7629428643', $response->id);
}
发布于 2012-08-26 14:44:51
计算响应和正确答案之间的差异,忽略任何过量的值。如果没有区别,一切都会好的;如果有,你就会得到完整的信息。
//some examples
$responseValues = array('success' => true, 'user_ip' => '212.20.30.40', 'id' => '7629428643'); //success
$errorResponseValues = array('success' => false, 'user_ip' => '212.20.30.40', 'id' => '7629428643'); //failure
$errorResponseValues2 = array('success' => false, 'user_ip' => '212.20.30.40', 'id' => '123'); //failure
$expectedValues = array('success' => true, 'id' => '7629428643'); //what is success
function whatIsWrong($reality, $expectation)
{
return array_uintersect_assoc($reality, $expectation, function($a, $b){return (int)($a == $b);}); //This is slightly dirty, I think the final implementation is up to you
}
var_dump(whatIsWrong($responseValues, $expectedValues)); //array()
var_dump(whatIsWrong($errorResponseValues, $expectedValues)); //array('success' => false)
var_dump(whatIsWrong($errorResponseValues2, $expectedValues)); //array('success' => false, id => 123)
然后您可以使用assertEqual(whatIsWrong(.)、array()),它应该在失败时输出差异,或者以几乎任何首选的方式处理它。
发布于 2012-08-03 06:04:10
如果assertTrue()
存储继承完整响应的布尔值,这就是我处理它的方式。请记住,这是一个味觉的问题。
private $lastResponse;
// $id given elsewhere
public function testAddAccount($id) {
$this->lastResponse = $this->addAccount($id);
}
private function addAccount($id) {
return $this->api->addAccount($id);
}
private function isLastResponseValid($response){
return $this->lastResponse->success === TRUE
&& $this->lastResponse->id === '7629428643';
}
https://stackoverflow.com/questions/11797030
复制相似问题