Skip to content

Instantly share code, notes, and snippets.

@shimabox
Last active June 22, 2017 05:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shimabox/0afd2148b99422b70d67 to your computer and use it in GitHub Desktop.
Save shimabox/0afd2148b99422b70d67 to your computer and use it in GitHub Desktop.
jsonを返すAPIのテストコード
<?php
/**
* メッセージ(json)を返すAPIと仮定
*
* あくまでもサンプルなので例外処理は入れていません
*/
class Sample
{
/**
* @var array
*/
protected $messages = array(
1 => "hoge",
2 => "piyo"
);
/**
* @param int $id
*/
public function getMessage($id)
{
$message = array("message" => $this->messages[$id]);
$this->echoJson(json_encode($message));
}
/**
* @param string $massage
*/
protected function echoJson($message)
{
header("Content-Type: application/json; charset=utf-8");
echo $message;
}
}
/**
* jsonを返すAPIのテストコード
*
* @group Sample
*/
class SampleTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function echoJsonはjson_encodeされた期待値を受け取っているか()
{
// モック化
$target = $this->getMockBuilder('Sample')
->setMethods(array('echoJson'))
->getMock()
;
// 期待値
$expected = json_encode(array("message" => "hoge"));
// 振る舞い指定
$target->expects($this->any())
// echoJsonは
->method('echoJson')
// json_encodeされた値を受け取るはずやと願いを込める
->with($this->equalTo($expected))
;
// test
$target->getMessage(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment