lundi 26 janvier 2015

How to catch invalid query errors in unit-testing

I introduced unit-testing a few month ago in our development process.


I just faced this problem : I wrote a test case for a simple function and relies on a database query. I used a mock object instead of the database adapter object. The tests passed, so far so good.


But it was a false positive. The mock object returned the expected resultset form the database (it must, since it is a mock object), but the real query did not return a valid resultset because of a typo.


One way I could solve this problem is to throw an exception if the query does not yield a recordset.



$db->query($query);
$resultset = $db->fetchAll();
if(!is_array($resultset)) throw new UnexpectedValueException("Query does not yield a result set");


This approach just makes the whole script fail (if the exception is not catched), and the test will fail for sure.


My question is : Is this the correct approach, or would you recommend something else ?


Aucun commentaire:

Enregistrer un commentaire