PHPでのユニットテストのデータストア
-
18-09-2019 - |
質問
私はPHPUnitのを使ってますが、それは難しい、それはデータストアとして使用されるオブジェクトのための良好なモックとスタブを作成するために見つけています。
例:
class urlDisplayer {
private $storage;
public function __construct(IUrlStorage $storage) { $this->storage = $storage; }
public function displayUrl($name) {}
public function displayLatestUrls($count) {}
}
interface IUrlStorage {
public function addUrl($name, $url);
public function getUrl($name);
}
class MysqlUrlStorage implements IUrlStorage {
// saves and retrieves from database
}
class NonPersistentStorage implements IUrlStorage {
// just stores for this request
}
例えば、異なる$の名前の2回の呼び出しで複数の可能な値を返すPHPUnitのスタブを持っているか?
編集:サンプルテストます:
public function testUrlDisplayerDisplaysLatestUrls {
// get mock storage and have it return latest x urls so I can test whether
// UrlDisplayer really shows the latest x
}
このテストでモックは私だけか一つの値を返すために文書でただし、URLの数を返す必要があります。
解決
あなたの質問は非常に明確ではありません - 私はあなたが異なる状況で異なる値を返すために、PHPUnitのモックオブジェクトを使用する方法を求めていると仮定します。
?PHPUnitのモッククラスを使用すると、カスタム関数を指定できます。(例:コールバック関数/メソッド) - それは何ができるかでは実質的に無制限である。
以下の例では、私はそのストレージにそれが呼び出されるたびに、次のURLを返しますモックIUrlStorageクラスを作成します。
public function setUp()
{
parent::setUp();
$this->fixture = new UrlDisplayer(); //change this to however you create your object
//Create a list of expected URLs for testing across all test cases
$this->expectedUrls = array(
'key1' => 'http://www.example.com/url1/'
, 'key2' => 'http://www.example.net/url2/'
, 'key3' => 'http://www.example.com/url3/'
);
}
public function testUrlDisplayerDisplaysLatestUrls {
//Init
$mockStorage = $this->getMock('IUrlStorage');
$mockStorage->expects($this->any())
->method('getUrl')
->will( $this->returnCallback(array($this, 'mockgetUrl')) );
reset($this->expectedUrls); //reset array before testing
//Actual Tests
$this->assertGreaterThan(0, count($this->expectedUrls));
foreach ( $this->expectedUrls as $key => $expected ) {
$actual = $this->fixture->displayUrl($key);
$this->assertEquals($expected, $actual);
}
}
public function mockGetUrl($name)
{
$value = current($this->expectedUrls);
next($this->expectedUrls);
//Return null instead of false when end of array is reached
return ($value === false) ? null : $value;
}
<時間>
また、時には単に必要な機能を皮肉って、実際のクラスを作成する方が簡単です。これは、十分に定義され、小さなインターフェースと特に容易である。
この特定のケースでは、私が代わりに以下のクラスを使用することをお勧めします:
class MockStorage implements IUrlStorage
{
protected $urls = array();
public function addUrl($name, $url)
{
$this->urls[$name] = $url;
}
public function getUrl($name)
{
if ( isset($this->urls[$name]) ) {
return $this->urls[$name];
}
return null;
}
}
?>
次に、あなたのユニットテストクラスには、単に以下のようなあなたのフィクスチャをインスタンス化します:
public function setUp() {
$mockStorage = new MockStorage();
//Add as many expected URLs you want to test for
$mockStorage->addUrl('name1', 'http://example.com');
//etc...
$this->fixture = new UrlDisplayer($mockStorage);
}
所属していません StackOverflow