I am writing an app that mainly consists of just creating, editing and reading records in database. I was persuaded that any app has to be covered with tests. I was told that it's a good practice to mock DB out of tests.

However in my app if I remove both HTTP and DB then there is almost nothing left. Data validation is inside models which cannot operate without db, at least not in my ORM. All that my functions do is operating on these models.

How am I going to test it? Maybe I should test at all?

Update: In the beginning I just wanted to write tests with db using Node.js and Sequelize. I had an issue with this approach. The issue is already asked about on SO here: https://stackoverflow.com/questions/49349326/seed-db-with-sequelize-seed-files-before-running-tests-with/52218311#52218311

The only answer suggests that I "shouldn't make real DB requests". So I decided to make a separate question about weather I really shouldn't or maybe I actually should.

  • Consider explaining what's so bad about my question please – Gherman Apr 9 at 13:44
  • Your question would be a better one if you addressed why you might want to mock out the DB in the first place. There's always good reasons for testing your application, and these reasons often drive how you approach your testing methods. – Robert Harvey Apr 9 at 15:11
  • @RobertHarvey because somebody told me it's better that way. OK, maybe it's indeed silly. – Gherman Apr 9 at 15:14
  • Ah, so you need to be clearer about what "better" means. – Robert Harvey Apr 9 at 15:16
  • 1
    There is no such thing as "good practices" without knowing what "good" means. Read this: softwareengineering.meta.stackexchange.com/a/8912 – Robert Harvey Apr 9 at 15:29

For a unit test that tries to test some component in isolation, mocking the DB is a good approach: this removes external dependencies that have to be set up first, and usually makes the tests a lot faster.

But maybe you don't need such fine-grained unit test. Especially for web apps, it is often straightforward to create high-level end to end tests that play through some user-visible scenario. Compare also BDD. Here, mocking the DB is not helpful. It is however helpful to be able to spin up a fresh test database for each test run. Techniques like using containers can be quite helpful here.

  • +1 whether or not you mock the db depends entirely on what you are aiming to verify with your tests. A mocked out DB where the logic is in a Stored Procedure is a very bad idea! – Liath Apr 9 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.