Last active
June 22, 2017 05:44
-
-
Save shimabox/0afd2148b99422b70d67 to your computer and use it in GitHub Desktop.
jsonを返すAPIのテストコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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