Php/phpunit/モックオブジェクト/テスト対象がconstructを含む場合
提供: 初心者エンジニアの簡易メモ
2015年5月20日 (水) 03:12時点における127.0.0.1 (トーク)による版 (ページの作成:「==サンプル== constructを含むテスト対象クラスの場合、 ==使い方== *Point.php (テスト対象クラス class Point { private $_point = 0;...」)
サンプル
constructを含むテスト対象クラスの場合、
使い方
- Point.php (テスト対象クラス
class Point
{
private $_point = 0;
public function add($point)
{
$this->_point += $point;
return $this;
}
public function getPoint()
{
return $this->_point;
}
}
- PointMockTest.php(テストクラス
require_once __DIR__ . '/../../application/Point.php';
class PointMockTest extends PHPUnit_Framework_TestCase
{
public function testGetPoint()
{
// Point クラスのスタブを作成します (作られたモックのメソッドの戻り値はnullで定義されている。
$stub = $this->getMock('Point');
// 第2パラメータにメソッド名を指定するとそのメソッドだけテスト(willで指定した値)に置き換わる。それ以外はPointクラスのメソッドをそのまま使う。(当たり前だがすべてを置き換えない場合は、mockは使わずにそのままnewする
// $stub = $this->getMock('Point', array('getPoint'));
// スタブの設定を行います
$stub->expects($this->any())
->method('getPoint')
->will($this->returnValue(10));
// その他のメソッドを指定してもnullとなる
// var_dump($stub->add(1));
// $stub->getPoint() をコールすると 10 を返すようになります
$this->assertThat($stub->getPoint(), $this->equalTo(10));
}
}
