| Prev | Next |
When you are writing tests for existing code, you have to write the same code fragments such as
public function testMethod()
{
}
over and over again. PHPUnit can help you by analyzing the code of the existing class and generating a skeleton test-case class for it.
Example 17.1: The Calculator class
<?php
class Calculator
{
public function add($a, $b)
{
return $a + $b;
}
}
?>
The following example shows how to generate a skeleton test class for a class named Calculator (see Example 17.1).
phpunit --skeleton Calculator
PHPUnit 3.2.10 by Sebastian Bergmann.
Wrote test class skeleton for Calculator to CalculatorTest.php.
For each method in the original class, there will be an incomplete test-case (see Chapter 10) in the generated test-case class.
Below is the output of running the generated test-case class.
phpunit --verbose CalculatorTest
PHPUnit 3.2.10 by Sebastian Bergmann.
CalculatorTest
I
Time: 0 seconds
There was 1 incomplete test:
1) testAdd(CalculatorTest)
This test has not been implemented yet.
/home/sb/CalculatorTest.php:54
OK, but incomplete or skipped tests!
Tests: 1, Incomplete: 1.
You can use @assert annotation in the documentation block of a method to automatically generate simple, yet meaningful tests instead of incomplete test-cases. Example 17.2 shows an example.
Example 17.2: The Calculator class with @assert annotations
<?php
class Calculator
{
/**
* @assert (0, 0) == 0
* @assert (0, 1) == 1
* @assert (1, 0) == 1
* @assert (1, 1) == 2
*/
public function add($a, $b)
{
return $a + $b;
}
}
?>
Each method in the original class is checked for @assert annotations. These are transformed into test code such as
/**
* Generated from @assert (0, 0) == 0.
*/
public function testAdd() {
$o = new Calculator;
$this->assertEquals(0, $o->add(0, 0));
}
Below is the output of running the generated test-case class.
phpunit CalculatorTest
PHPUnit 3.2.10 by Sebastian Bergmann.
....
Time: 0 seconds
OK (4 tests)
Table 17.1 shows the supported variations of the @assert annotation and how they are transformed into test code.
Table 17.1. Supported variations of the @assert annotation
| Annotation | Transformed to |
|---|---|
@assert (...) == X
|
assertEquals(X, method(...))
|
@assert (...) != X
|
assertNotEquals(X, method(...))
|
@assert (...) === X
|
assertSame(X, method(...))
|
@assert (...) !== X
|
assertNotSame(X, method(...))
|
@assert (...) > X
|
assertGreaterThan(X, method(...))
|
@assert (...) >= X
|
assertGreaterThanOrEqual(X, method(...))
|
@assert (...) < X
|
assertLessThan(X, method(...))
|
@assert (...) <= X
|
assertLessThanOrEqual(X, method(...))
|
@assert (...) throws X
|
@expectedException X
|
| Prev | Next |
Copyright © 2005-2011 Sebastian Bergmann.