PHPでテスト駆動開発を写経してみたのでその記録です。
本記事では第2章のみ紹介します。
過去記事
- テスト駆動開発をPHPで写経-第1章 - Qiita
所感
今回はほぼテキスト通りに行えました
実施
Dollarオブジェクトの状態が変わらないことを期待するテストに修正
diff --git a/tests/MoneyTest.php b/tests/MoneyTest.php
index b753708..d47dc01 100644
--- a/tests/MoneyTest.php
+++ b/tests/MoneyTest.php
@@ -8,7 +8,9 @@ require_once(dirname(__FILE__)."/../src/Dollar.php");
class MoneyTest extends TestCase {
public function testMultiplication() {
$five = new Dollar(5);
- $five->times(2);
- $this->assertEquals(10, $five->amount);
+ $product = $five->times(2);
+ $this->assertEquals(10, $product->amount);
+ $product = $five->times(3);
+ $this->assertEquals(15, $product->amount);
}
}
テスト実行
PHPUnit 7.5.17 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 18 ms, Memory: 4.00 MB
There was 1 failure:
1) money\MoneyTest::testMultiplication
Failed asserting that null matches expected 10.
/Users/ok/data/projects/tdd-php/tests/MoneyTest.php:12
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
状態を変えずに新しいオブジェクトを返すように修正
diff --git a/src/Dollar.php b/src/Dollar.php
index 8819734..02b1f28 100644
--- a/src/Dollar.php
+++ b/src/Dollar.php
@@ -10,6 +10,6 @@ class Dollar {
}
function times($multiplier) {
- $this->amount *= $multiplier;
+ return new Dollar($this->amount * $multiplier);
}
}
テスト実行
PHPUnit 7.5.17 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 17 ms, Memory: 4.00 MB
OK (1 test, 2 assertions)