PHP Enhance Unit Testing Framework Full Example

Feeds

RSS Feed

<< July | August | September >>

Monday, 15th August 2011

I thought I would share an entire PHP test, which shows off the set up and tear down methods, three tests that all use the assertion helper, which has been stuffed into a private variable - and it is all completely annotated with information on the naming conventions and concepts. Obviously you wouldn't use this volume of commenting in real life (I've read Uncle Bob!) but this helps to explain how you would write your tests.

For the most up-to-date examples, please visit the Enhance PHP website.

It is pretty similar to what you would do in other languages.

<?php
// Naming: Each fixture must end with the word "TestFixture".
//     Suggested naming is to include the following
//     [class name]TestFixture
//     for example
//     MyClassTestFixture
class ExampleTestFixture {

    // SetUp
    // Naming: The method is optional, but if present you must call it "SetUp".
    // Usage: You can use the SetUp method to pre-configure things you want to use in all your tests.
    public function SetUp() {

    }
    
    // TearDown
    // Naming: The method is optional, but if present you must call it "TearDown".
    // Usage: You can use the TearDown method to re-set things after all you tests.
    public function TearDown() {
    
    }

    // Test
    // Naming: Each test function must end with the word "Test".
    //        Suggested naming is to include the following
    //     [function name][test scenario][expected result]Test
    //     for example, you could use underscores or "With" and "Expect" keywords to construct the name
    //     AddTwoNumbers_3And2_Expect5Test or AddTwoNumbersWith3and2Expect5Test
    // Usage: We recommend using the Arrange, Act, Assert syntax as shown below
    public function AddTwoNumbersWith3and2Expect5Test() {
        // Arrange
        $target = new ExampleClass();

        // Act
        $result = $target->AddTwoNumbers(3, 2);

        // Assert
        Assert::AreEqual(5, $result);
    }
    
    // Test
    public function AddTwoNumbersWith4and2Expect6Test() {
        // Arrange
        $target = new ExampleClass();

        // Act
        $result = $target->AddTwoNumbers(4, 2);

        // Assert
        Assert::AreEqual(6, $result);
    }
    
    // Test
    // This is an example of a failing test
    public function AddTwoNumbersWith5and5Expect9Test() {
        // Arrange
        $target = new ExampleClass();

        // Act
        $result = $target->AddTwoNumbers(5, 5);

        // Assert
        // We deliberately assert the wrong result to show an error
        Assert::AreEqual(9, $result);
    }
}
?>

You Are Here: Home » Blog » PHP Enhance Unit Testing Framework Full Example