EECS 394 Software Project Management Chris Riesbeck Database Testing Thursday, May 12, 2011
Database testing problems � Real database changes constantly � so tests looking for specific results may fail � Real database should not have dummy test data � confuses users and internal queries � Real database should not be changed by tests for adding and editing data � Test databases have to be cloned for each test 2 Thursday, May 12, 2011
Solutions � Mock objects � see BDD and Mock Objects slides � great for unit testing � doesn't test db code actually works! � Database fixtures � frameworks for loading static test data into a new test db on every test � some support loading data from CSV, XML and other text files � use for integration testing 3 Thursday, May 12, 2011
CakePHP Example: The fixture <?php // app/tests/fixtures/post_fixture.php class PostFixture extends CakeTestFixture { the db schema var $name = 'Post'; var $fields = array( 'id' => array('type' => 'integer', 'key' => 'primary'), 'title' => array('type' => 'string', 'length' => 50, 'null' => false), 'body' => 'text', 'created' => 'datetime' the test data ); var $records = array( array ('id' => 1, 'title' => 'First Post', 'body' => 'First Post Body', 'created' => '2007-03-18 10:39:23'), array ('id' => 2, 'title' => 'Second Post', 'body' => 'Second Post Body', 'created' => '2007-03-18 10:41:23'), array ('id' => 3, 'title' => 'Third Post', 'body' => 'Third Post Body', 'created' => '2007-03-18 10:43:23') ); } ?> 4 Thursday, May 12, 2011
CakePHP Example: The test case <?php // app/tests/cases/models/post.test.php class PostTestCase extends CakeTestCase { tell CakePHP to use the var $fixtures = array( 'app.post' ); test Post fixture function testGetRecentShouldReturnLastTwoPosts() { magic CakePHP to $this->Post =& ClassRegistry::init('Post'); use test suite db $expected = array( array('Post' => array ('id' => 3, 'title' => 'Third Post', 'body' => 'Third Post Body', 'created' => '2007-03-18 10:43:23')), array('Post' => array ('id' => 2, 'title' => 'Second Post', 'body' => 'Second Post Body', 'created' => '2007-03-18 10:41:23')) ); $this->assertEqual($this->Post->getRecent(2), $expected); } } ?> 5 Thursday, May 12, 2011
CakePHP Example: The code <?php // app/models/post.php class Post extends AppModel { var $name = 'Post'; function getRecent($count) { $params = array( normal db code 'limit' => $count, 'order'=>array('Post.created DESC') ); return $this->find('all', $params); } } ?> 6 Thursday, May 12, 2011
Fixtures for various languages � Ruby � http://ar.rubyonrails.org/classes/Fixtures.html � PHP � http://book.cakephp.org/view/1201/Preparing-test- data � Django � http://docs.djangoproject.com/en/1.3/howto/initial- data/ � Java � http://onjava.com/onjava/2004/01/21/dbunit.html 7 Thursday, May 12, 2011
Recommend
More recommend