TestResponse 是一個輔助測試 response 用的物件,它內建混入(mixin)了 Response 物件功能:
use Macroable { __call as macroCall ; } public function __call ($method , $args ) { if (static ::hasMacro ($method )) { return $this ->macroCall ($method , $args ); } return $this ->baseResponse->{$method }(...$args ); } public function __get ($key ) { return $this ->baseResponse->{$key }; }
並提供了許多 assert 方法,如 assertSuccessful()
:
public function assertSuccessful ( ) { PHPUnit ::assertTrue ( $this ->isSuccessful (), 'Response status code [' .$this ->getStatusCode ().'] is not a successful status code.' ); return $this ; }
這讓測試程式碼變得更加容易理解。
大部分的 assert 方法都是很單純的包裝 Response 的結果,少部分比較特別的如 View:
public function assertViewIs ($value ) { $this ->ensureResponseHasView (); PHPUnit ::assertEquals ($value , $this ->original->getName ()); return $this ; } protected function ensureResponseHasView ( ) { if (! isset ($this ->original) || ! $this ->original instanceof View) { return PHPUnit ::fail ('The response is not a view.' ); } return $this ; }
JSON 的 assert 設計也是非常厲害,如看是否有 JSON 片段 assertJsonFragment()
:
public function assertJsonFragment (array $data ) { $actual = json_encode (Arr ::sortRecursive ( (array ) $this ->decodeResponseJson () )); foreach (Arr ::sortRecursive ($data ) as $key => $value ) { $expected = $this ->jsonSearchStrings ($key , $value ); PHPUnit ::assertTrue ( Str ::contains ($actual , $expected ), 'Unable to find JSON fragment: ' .PHP_EOL.PHP_EOL. '[' .json_encode ([$key => $value ]).']' .PHP_EOL.PHP_EOL. 'within' .PHP_EOL.PHP_EOL. "[{$actual} ]." ); } return $this ; } protected function jsonSearchStrings ($key , $value ) { $needle = substr (json_encode ([$key => $value ]), 1 , -1 ); return [ $needle .']' , $needle .'}' , $needle .',' , ]; }