Now let's write our first test! To create a test you simply have to define a method which starts with the word "test".
It doesn't matter if you use an underscore after the word "test" or not! As long as "test" is the first word, it doesn't matter. Let's see our first test:
function testFileExists() { $this->assertTrue($this->file->exists()); clearstatcache(); $this->assertTrue(file_exists($this->file->filename)); } |
In this test, we check for the file existence twice (paranoid?) using the method assertTrue() which will insure that the method exists() will return true!
Then we use the built-in function file_exists() to double check that the file truely exists!
I'll tell you later why we checked twice.
UnitTesting in SimpleTest depends heavily on assertions! Like in our previous test we used the method assertTrue() which will require the argument passed to it to be true in order to pass or it will fail!
It's worth saying that assertTrue() will pass as long as the argument is neither 0 nor false. So assertTrue("String") will pass.
If you want to be strict about this, use assertIdentical() which will check the value and the type. e.g. assertIdentical("true", true) will fail!
SimpleTest has many assert*() methods and in our UnitTestCase class we have these:
|
assertTrue($x) |
Fail if $x is false |
|
assertFalse($x) |
Fail if $x is true |
|
assertNull($x) |
Fail if $x is set |
|
assertNotNull($x) |
Fail if $x not set |
|
assertIsA($x, $t) |
Fail if $x is not the class or type $t |
|
assertNotA($x, $t) |
Fail if $x is of the class or type $t |
|
assertEqual($x, $y) |
Fail if $x == $y is false |
|
assertNotEqual($x, $y) |
Fail if $x == $y is true |
|
assertIdentical($x, $y) |
Fail if $x == $y is false or a type mismatch |
|
assertNotIdentical($x, $y) |
Fail if $x == $y is true and types match |
|
assertReference($x, $y) |
Fail unless $x and $y are the same variable |
|
assertCopy($x, $y) |
Fail if $x and $y are the same variable |
|
assertWantedPattern($p, $x) |
Fail unless the regex $p matches $x |
|
assertNoUnwantedPattern($p, $x) |
Fail if the regex $p matches $x |
|
assertNoErrors() |
Fail if any PHP error occoured |
|
assertError($x) |
Fail if no PHP error or incorrect message |
|
assertErrorPattern($p) |
Fail unless the error matches the regex $p |
We will only need some these assestions to test our current unit :)
Note that you could pass additional argument to all these methods which will be the message to be displayed in case the test fails e.g. $this->assertTrue(false, 'Passing false to assertTrue faild!').
Don't worry though, because the error messages generated by SimpleTest are very informative so no need to bother writing new messages.