Question

I want to execute several tests in a testcase / testsuite (via selenium) and hook a database test onto the end of every tearDown (with assert which can't be called in tearDown).

So the workflow would be:

  • Setup the Connection to the database and the Schema in setUpBeforeClass()
  • Setup the Database (only the contents) in setUp()
  • Execute test01
  • TearDown contents
  • Assert if every Table in Database has a rowCount of Zero.

So is there a way to hook a additional assert onto the end of every tearDown?

I tried to do the Setup in assertPreConditions and the tearDown in assertPostConditions but thats kind of ugly.

Thx in advance

Was it helpful?

Solution

It seems you can use an assert anywhere, even in tearDown(). This test case (save as testTearDown.php, run with phpunit testTearDown.php) correctly gives a fail:

class TearDownTest extends PHPUnit_Framework_TestCase
{

/** */
public function setUp(){
    echo "In setUp\n";
    //$this->assertTrue(false);
    }

/** */
public function tearDown(){
    echo "In tearDown\n";
    $this->assertTrue(false);
    }

/** */
public function assertPreConditions(){
    echo "In assertPreConditions\n";
    //$this->assertTrue(false);
    }

/** */
public function assertPostConditions(){
    echo "In assertPostConditions\n";
    //$this->assertTrue(false);
    }

/**
*/
public function testAdd(){
    $this->assertEquals(3, 1+2);
    }

}

But, one rule of thumb I have is: if the software is making my life difficult, maybe I'm doing something wrong. You wrote that after the tearDown code has run you want to: "Assert if every Table in Database has a rowCount of Zero."

This sounds like you want to validate your unit test code has been written correctly, in this case that tearDown has done its job correctly? It is not really anything to do with the code that you are actually testing. Using the phpUnit assert mechanisms would be confusing and misleading; in my sample above, when tearDown asserts it tells me that testAdd() has failed. If it is actually code in tearDown() that is not working correctly, I want to be told that instead. So, for validating your unit test code, why not use PHP's asserts:

So I wonder if the tearDown() function you want could look something like this:

public function tearDown(){
    tidyUpDatabase();
    $cnt=selectCount("table1");
    assert($cnt==0);
    $cnt=selectCount("table2");
    assert($cnt==0);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top