Java言語で学ぶリファクタリング入門 を購入した: 006
- http://homepage2.nifty.com/youichi_kato/src.html
ReplaceTypeCodeWithClass (2007-02-10)
refsrc-2007-02-10.tgz
カバレーッジレポートのスクリーンショット
として、ReplaceTypeCodeWithClass の章のソースコードを maven 化プロジェクトに追加したものを公開しました。
さらに、以前のコードを以下の様に変更もしています。
変更したのは、Robot クラスの実装とそのテストコードです。
いままでは、テストコードはダミーだったし、Robot.java 中では if ... else の最後の else 節には到達することはないとして、テストでその部分が実行されないのは良しとしていました。
しかし、null のケースを忘れていたのに気がついたのです。
そこで、次のようにして変更してみました。
Robot.java では
...
public void order(final Robot.Command command) {
if (command == Command.WALK) {
System.out.println(this._name + " walks.");
} else if (command == Command.STOP) {
System.out.println(this._name + " stops.");
} else if (command == Command.JUMP) {
System.out.println(this._name + " jumps.");
} else {
// command == null などのケース
System.out.println("Command error. command = " + command);
assert false;
}
}
としました。
このコードのテストを次のようにしました。
@Test
public void testRobot() {
final Robot robot = new Robot("test");
// Expected
final String expected = getExpectedOutput("Command error. command = null");
// Actual
try {
robot.order(null);
final String actual = getActualOutput();
// Assert
assertEquals(expected, actual);
} catch (AssertionError ex) {
// -ea で assert が有効な場合はここにくる。
assertEquals(true, true);
} catch (Throwable th) {
assertEquals(true, false);
}
}
eclipse から junit テストを実行するときは、assert が無効になっている (-ea を VM オプションで指定していないから)
ので、assertEqual(...) でのチェックがされます。
mvn から test を実行すると、assert が有効になっているので、AssertionError が throw されることをチェックしています。
最近のコメント