mardi 16 janvier 2018

How to test a function that has side effects?

Given a function that does some operation on a database for instance.

In python, it would look like the following:

def dao_transfer(cnx, account_id1, account_id2, money):
   spam = cnx.execute('query 1', account_id1)
   egg = cnx.execute('query 2', account_2, spam)
   return egg

What I do in my unit tests is that I mock the cnx object, and only check that cnx.execute is called and that dao_transfer returns the last mock return value of cnx.execute.

I have the feeling that this poor testing.

What Django does, is that it doesn't unittest functions that interacts with the database but instead, do what I call integration tests ie. you spawn a full database, you load it with some initial data, execute your side-effect powered function and check that the database is in the correct state.

I could do that, but I'd rather prefer unittests. Is there an approach to unit testing side effect function that doesn't rely on checking every single side effect function calls arguments?

Is there pure approach to IO that allows better unit testing?

Aucun commentaire:

Enregistrer un commentaire