phpunit-testingsimpletest

Testing with PHP SimpleTest


I'm running into an error while trying to run some simple tests with SimpleTest for PHP.

Currently, I'm extending the class UnitTestCase as per the documentation. I'm trying to test different aspects of my class within a method. Here is my class:

<?php
class SimpleClass extends UnitTestCase {

    public function __construct() {
        $this->test();
    }

    private function test() {
        $x = true;
        $this->assertTrue($x, 'x is true');
    }
}

I've tried extending the TestSuite class and using the syntax in the documentation but I got the same error:

Fatal error: Call to a member function getDumper() on a non-object in /simpletest/test_case.php on line 316

Any ideas on how I could do this or am I approaching class testing wrong?


Solution

  • Don't use a constructor in your test!

    SimpleTest allows you to create classes with methods. If their name starts with "test", it is automatically recognized as a testing method that will get called if you start the test suite.

    You created a constructor which calls your test method, and does an assertion without all the setup taking place, so SimpleTest does not have a reporter class that is needed to wrap it's test findings into a nice output.

    Read the tutorial more closely, and you'll find some hints on how to set up a test suite or how to start a single test:

    Let us suppose we are testing a simple file logging class called Log in classes/log.php. We start by creating a test script which we will call tests/log_test.php and populate it as follows...

    Code example adapted from the documentation:

    <?php
    require_once('simpletest/autorun.php');
    require_once('../classes/log.php');
    
    class TestOfLogging extends UnitTestCase {
        function testLogCreatesNewFileOnFirstMessage() {
            $this->assertTrue(true);
        }
    }
    ?>
    

    Note there is no constructor, and the autorun file will take care to run the test if this file is executed with PHP.