クラスは、実際にテストしているものではない images() の文字列を返します。
class WebsiteHasImage{
public function images(){
$website = 'http://somedomain.com/images/img.jpg';
return $website;
}
}
class WebsiteHasImageTest extends PHPUnit_Framework_TestCase
{
public function testSuccess()
{
WebSiteImage = new WebSiteHasImage();
$this->assertEquals('http://somedomain.com/images/img.jpg', $WebSiteImage->images(), 'Check returned File Name is correct');
}
}
これで完了したのは、画像文字列が正しいことをテストすることだけです。
別の呼び出しで画像を読み取って比較することもできますが、それには Web サイトが稼働している必要があります。
必要に応じて、呼び出しで images/img.jpg の現在のアプリケーション ディレクトリを調べ、いくつかのテスト (バイト サイズが適切かどうかなど) を実行して、画像を検証することができます。
Web サイトを読み取ってコンテンツを返そうとすることもできますが、これには Web サイトが必要です。したがって、コードをテストするには、Web サイトのデータを返すクラスを用意し、そのクラスをモックして固定文字列を返します。これに対してテストを記述して、クラスのコードが画像を正しく抽出することを確認します。次に、クラスは画像の存在をテストし、再び、それを常に返すようにモックして、コードが何をするかをテストします。
public function GetWebPageContents($HTTPAddress)
{
$HTML = ... // Code that reads the contents
return $HTML;
}
public function GetImageList($HTML)
{
$ImageList = array();
... // Code to find all images, adding to ImageList
return $ImageList;
}
テストクラスの追加
public function testGetWebPageContents()
{
$HTMLText = '<html><body><img scr=""></img></body><</html>'; // Fill this with a sample webpage text
$MockClass = $this->getMock('WebsiteHasImage', array('GetWebPageContents'));
// Set up the expectation for the GetWebPageContents() method
$MockClass->expects($this->any())
->method('GetWebPageContents')
->will($this->returnValue($HMTLText));
// Create Test Object
$TestClass = new MockClass();
$this->assertEquals($HTMLText, $TestClass->GetWebPageContents('http://testaddress.com'), 'Validate Mock HTML return'); // Address is garbage as it does not matter since we mocked it
$WebsiteTest = new WebsiteHasImage();
$ImageList = $WebsiteTest->GetImageList($HTMLText);
$this->assertEquals(1, count($ImageList), 'Count Total Number of Images');
$this->assertEquals('images/img.jpg', $ImageList[0], 'Check actual image file name from dummy HTML parsing');
... // More tests for contents
}
ここで、最良の変更は、読み取ったデータをクラス内で使用することです。そのためには、Web サイトから読み取った後、通常どおり HTML コードをクラスに渡します。テストでは、コンストラクターで Mock オブジェクトを使用して、または Set を介して、読み取りを行うオブジェクトを渡します。このトピックの詳細については、依存性注入、モック オブジェクトなどを Google 検索してください。