В последнее время мне нравится решать проблему TDD / модульное тестирование . В последнее время я больше не программирую на PHP, но это то, что я придумал. Честно говоря, я на самом деле посмотрел примеры кода здесь и выбрал тот, который мне показался правильным. Затем я хотел проверить это путем модульного тестирования, используя тесты, которые вы предоставили выше.
класс TimeTest
require_once 'PHPUnit/Framework.php';
require_once 'Time.php';
class TimeTest extends PHPUnit_Framework_TestCase
{
protected $time;
protected function setUp() {
$this->time = new Time(10, 50);
}
public function testConstructingTime() {
$this->assertEquals("10:50", $this->time->getTime());
$this->assertEquals("10", $this->time->getHours());
$this->assertEquals("50", $this->time->getMinutes());
}
public function testCreatingTimeFromString() {
$myTime = Time::create("10:50");
$this->assertEquals("10", $myTime->getHours());
$this->assertEquals("50", $myTime->getMinutes());
}
public function testComparingTimes() {
$timeEquals = new Time(10, 50);
$this->assertTrue($this->time->equals($timeEquals));
$timeNotEquals = new Time(10, 44);
$this->assertFalse($this->time->equals($timeNotEquals));
}
public function testRoundingTimes()
{
// Round test time.
$roundedTime = $this->time->round();
$this->assertEquals("10", $roundedTime->getHours());
$this->assertEquals("45", $roundedTime->getMinutes());
// Test some more times.
$timesToTest = array(
array(new Time(1,00), new Time(1,12)),
array(new Time(3,15), new Time(3,28)),
array(new Time(1,00), new Time(1,12)),
);
foreach($timesToTest as $timeToTest) {
$this->assertTrue($timeToTest[0]->equals($timeToTest[0]->round()));
}
}
}
Время урока
<?php
class Time
{
private $hours;
private $minutes;
public static function create($timestr) {
$hours = date('g', strtotime($timestr));
$minutes = date('i', strtotime($timestr));
return new Time($hours, $minutes);
}
public function __construct($hours, $minutes) {
$this->hours = $hours;
$this->minutes = $minutes;
}
public function equals(Time $time) {
return $this->hours == $time->getHours() &&
$this->minutes == $time->getMinutes();
}
public function round() {
$roundedMinutes = $this->minutes - ($this->minutes % 15);
return new Time($this->hours, $roundedMinutes);
}
public function getTime() {
return $this->hours . ":" . $this->minutes;
}
public function getHours() {
return $this->hours;
}
public function getMinutes() {
return $this->minutes;
}
}
Выполнение теста
alfred@alfred-laptop:~/htdocs/time$ phpunit TimeTest.php
PHPUnit 3.3.17 by Sebastian Bergmann.
....
Time: 0 seconds
OK (4 tests, 12 assertions)