jeudi 1 janvier 2015

Should database connections be mocked?

I'm trying to apply unit testing to a project I'm working on. I work with Python an MySQLdb but I think this discussion is language-agnostic. I want to test a function, let's call it foobar(). It executes SQL queries that look similar to this:



cursor.execute("SELECT * FROM my_table WHERE a == " +varA+ " AND b < " +varB)


There is a little bit of complexity going on in the function. How and how often cursor.execute(query) gets called depends on foobar's arguments.


Now I'm unsure if I should mock the database connection cursor. If I don't, it's bad because the test depends on the availability of a DB server. If I do, it's bad because the mock has to know which queries will be called. But the exact queries are an implementation detail. E.g. whether the queries are written in lower- or uppercase does not affect the correctness of foobar. But changing that will break the test. The test will also be hard to read because of the somewhat complex mock object.


Is this a case of choosing the lesser evil? Is there a third way?


Aucun commentaire:

Enregistrer un commentaire