2

I understand unit testing and its value but I’m really struggling when I have to mock databases or other external resources. It’s normal or others have this annoyance?

Comments
  • 2
    I rarely mock DB. If I have an ORM I mock that and if not I gather the DB calls in one class and mock that.

    The SQL queries I try in other ways.
  • 0
    @Voxera thanks for the advice, my current circumstances (heavy usage of multiple NoSQL) makes a sane use of ORMs sane but I can try to collect the calls in a class 😊
  • 3
    If you're using an ORM then you should be mocking that if possible, as testing the stability of the database system isn't part of the unit testing. The unit tests should test code, meaning you should assume the database response (either success or error, to handle all cases)

    Not sure what you're working with, in Java the Mockito library is ideal for this. If you're using something else that uses some kind of dependency injection that you can probably create your own mocked class implementation of the actual ORM interface and mock that manually...

    Intuitively though, the whole point of mocking the ORM is that it really isn't your job to make sure the database itself works, just the code that uses the calls and results :)
  • 3
    Another note. If you find that the unit tests your writing needs to be complex, it's a good sign that your design is too complex.

    If you start with the tests first, you'll notice this complexity sooner and can iterate designs faster.
  • 1
    if it's automated, I don't see it being a nuisance
  • 1
    Don't mock what you don't own.
Add Comment