Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.