Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phpunit - reusing mock objects for multiple test suites

I am curious as to how others approach this. Writing a test ain't so bad, but mocking kind of sucks a bit and cuts my flow. Is it ok for one to have a 'fixtures' directory and have say mock_db.php for example with just that particular mock declaration?

Going one step further, would it be bad practice to have those mocks abstracted in a function?

Ie:

 // function to include a db mock
   include_once 'test/fixtures/dbmock.php';

   $mockMYSQL = $dbmock('mysql', 'db1');
   $mockMSSQL = $dbmock('mssql', 'db2');

JUst interested to know how other experienced testers handle this. I'm writing scripts to sync 2 databases so this example may become very relevant.

like image 679
stefgosselin Avatar asked May 19 '11 06:05

stefgosselin


1 Answers

I would go either with inheritance - having the common mock objects created and returned in protected get* methods in common parent test case class.

Or you can create cleaner and standalone class that you would instantiate in your test suites and let it create your mock objects. I would prefer this way, but it has one downside - you probably can not or should not use the PHPUnit_Framework_TestCase getMock() method. I recommend you to look at this method and try to use its logic in your standalone class.

Including global functions is not very OOP, it's rather magic that PHP allows but you should avoid it :)

like image 103
Ondřej Mirtes Avatar answered Oct 11 '22 03:10

Ondřej Mirtes