如何测试对象的多个属性

Rad*_*mko 7 php phpunit

我从API获取JSON结构,需要检查成功响应是否具有两个具有特定值的特定属性.

关键问题:

  1. 我无法比较整个对象,因为有一些属性可能会因每个请求而异
  2. 我不能写两个测试(对于每个属性),因为只有当两个属性都匹配正确的值时才能将其视为成功响应.

成功响应示例:

{
    'success': true,
    'user_ip': '212.20.30.40',
    'id': '7629428643'
}
Run Code Online (Sandbox Code Playgroud)

肮脏的解决方案将是

<?php
public function testAddAccount() {
    $response = $this->api->addAccount( '7629428643' );

    $this->assertTrue(
        $response->success === TRUE &&
        $response->id === '7629428643'
    );
}
Run Code Online (Sandbox Code Playgroud)

但我认为必须有更好更清洁的解决方案,有吗?

Sem*_*Sem 0

如果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';
}
Run Code Online (Sandbox Code Playgroud)