class MyClass {
private $numeric;
public function MyMethod($numeric)
{
if (! is_numeric($numeric)) {
throw new InvalidArgumentException
}
$this->numeric = $numeric;
}
}
1 -クラスが存在するかどうかをテストする必要がありますか?
PHPUnit には、assertPreConditions、setUp など、自動的に実行されるいくつかのメソッドがあります。これらのメソッド内で、assertTrue および class_exists? を使用してクラスが存在するかどうかを確認する必要があります。例:
protected function assertPreConditions()
{
$this->assertTrue(class_exists("MyClass"), "The class does not exists.");
}
2 -メソッドが存在するかどうかを確認する必要がありますか? はいの場合、このテストは個別のテストにする必要がありますか、それとも各単体テスト内にする必要がありますか?
数値型パラメーターのみを受け入れるメソッドがあるとします。つまり、2 つのテストがあります。1 つは正しいパラメーターを使用したテストで、もう 1 つは例外を予期する不適切なメソッドを使用したテストですよね? このメソッドを記述する正しい方法は...
こちらです:
public function testIfMyMethodExists()
{
$this->assertTrue(method_exists($MyInstance, "MyMethod"), "The method does not exists.");
}
/**
* @depends testIfMyMethodExists
* @expectedException InvalidArgumentExcepiton
*/
public function testMyMethodWithAValidArgument()
{
//[...]
}
/**
* @depends testIfMyMethodExists
* @expectedException InvalidArgumentExcepiton
*/
public function testMyMethodWithAnInvalidArgument()
{
//[...]
}
それともこの道?
public function testMyMethodWithAValidArgument()
{
$this->assertTrue(method_exists($MyInstance, "MyMethod"), "The method does not exists.");
}
/**
* @expectedException InvalidArgumentExcepiton
*/
public function testMyMethodWithAnInvalidArgument()
{
$this->assertTrue(method_exists($MyInstance, "MyMethod"), "The method does not exists.");
//[...]
}
なぜ?
3 - @covers と @coversNothing の本当の目的は何ですか?
PHPUnit の作成者である Sebastian Bergmann が、常にメソッドとクラスに @covers と @coversNothing を記述し、これらのオプションを xml に追加することをお勧めします。
mapTestClassNameToCoveredClassName="true"
forceCoversAnnotation="true"
そしてホワイトリストで:
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php"></directory>
</whitelist>
しかし、それの本当の必要性は何ですか?
4 -別のメソッドを呼び出すコンストラクターをテストする正しい方法は?
すべて問題ないようですが、テストではそうではありません。
メソッド「MyMethod」で例外が発生することを期待して、有効な引数と無効な引数を使用してテストを行っても、コンストラクターに誤った値を入力すると発生しません (テストは失敗します)。
そして、有効な引数でテストすると、コード カバレッジは 100% になりません。
public function __construct($numeric)
{
$this->MyMethod($numeric);
}