PHPUnit: use different dataset on every test in a testcase

PHPUnit offers the possibility to perform tests based in database fixtures. The common way is like described in the PHPUnit documentation.

But what if you just want to have a small and different dataset on every test?

My way to achieve that is the following:

  1. create a minimal dataset with a table and a column that exist in your database, because getDataSet() has to return an object that implements the PHPUnit_Extensions_Database_DataSet_IDataSet interface.
    protected function getDataSet(){
           return $this->createXMLDataSet('testfile.xml);
    }
    

    The minimal dataset might look like the following:

    <dataset>
    	<table name="tbl_test">
    		<column>id</column>
    		<row>1</row>
    	</table>
    </dataset>
    
  2. implement the getTearDownOperation function which is called after each test
    • resets the database to be empty
    protected function getTearDownOperation() {
    	return PHPUnit_Extensions_Database_Operation_Factory::DELETE_ALL();
    }
    
  3. create your own setup function
    • copied from the original SetUp function in PHPUnit_Extensions_Database_TestCase
    • added a parameter to mySetup function to carry the dataset
    • call PHPUnit_Framework_TestCase::SetUp() instead of parent::SetUp()
    protected function mySetup($dataSet){
    	PHPUnit_Framework_TestCase::SetUp();
    
    	$this->databaseTester = NULL;
    
    	$this->getDatabaseTester()->setSetUpOperation(
    		$this->getSetUpOperation()
    	);
    	$this->getDatabaseTester()->setDataSet($dataSet);
    	$this->getDatabaseTester()->onSetUp();
    }
    
  4. use it on every test function
    public testMyTest(){
    	$this->mySetup(
    		$this->createXMLDataSet('testCase.xml')
    	);
    	...
    }
    

Enjoy.

Dieser Beitrag wurde unter PHP, phpunit abgelegt und mit , , , verschlagwortet. Setze ein Lesezeichen auf den Permalink.