PHPコードカバレッジの計測
11月 6th, 2008 by
key
※当たり障り無い内容なので某所から転記
xdebugとlimeを使うと出来る。
試験用に短い関数を作る。
<?php
function test_function($a) {
switch ($a) {
case "aaa":
return true;
case "bbb":
return false;
case "ccc":
default:
return null;
}
}
test_function()のテストを書く。カバレッジを計測するため、意図的に引数にcccを与えた場合の処理は書いていない。
<?php
require("/opt/local/lib/php/symfony/vendor/lime/lime.php");
require("function.php");
$t = new lime_test(2, new lime_output_color());
$t->is(test_function("aaa"), true);
$t->is(test_function("bbb"), false);
?>
テストの実施とカバレッジ測定を行うコードを書く。
<?php
require("/opt/local/lib/php/symfony/vendor/lime/lime.php");
// テストの実施
$h = new lime_harness(new lime_output_color());
$h->register("functionTest.php");
$h->run();
// カバレッジ計測
$c = new lime_coverage($h);
$c->base_dir = realpath(dirname(__FILE__));
$c->register($c->base_dir."/function.php");
$c->run();
?>
実行すると以下のようになる。
$ php functionTestDo.php functionTest.........................................................ok All tests successful. Files=1, Tests=2 function 57% TOTAL COVERAGE: 57%
57%しかカバーされてないのでこのテストはイケてない。functionTest.phpを編集し、lime_test()への引数を増やしてファイルの末尾にテストを足した。
<?php
require("/opt/local/lib/php/symfony/vendor/lime/lime.php");
require("function.php");
$t = new lime_test(3, new lime_output_color());
$t->is(test_function("aaa"), true);
$t->is(test_function("bbb"), false);
$t->is(test_function("ccc"), null);
再度実行してみると…
$ php functionTestDo.php ...........................................ok All tests successful. Files=1, Tests=3 function 100% TOTAL COVERAGE: 100%
カバレッジ100%!
ユニットテストにしか使えないかな?
遷移を伴う複雑なテストケースに適用出来るかは今後調べてみる(かも知れない)。