U
U
user_of_toster2020-01-03 18:36:45
Software testing
user_of_toster, 2020-01-03 18:36:45

When to mock, when not to mock in unit testing?

There is a function with a bunch of dependencies. Pseudocode:

register_user (login, pass, email) {
    if data_valid (login, pass, email) then
        hash = generate_hash(pass)
        add_to_database(login, hash, email)
        send_email(email)
    else
       return 'invalid data'
}

What's better?
  1. try to wet everything possible;
  2. try not to cheat as much as possible and try to create real conditions - raise a fake database, fill it in, actually create a hash, actually send a letter to the raised server


Please justify your answer.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2020-01-03
@user_of_toster

It's best to never get wet if possible.
Mock only in one of the following situations:
- The original takes too long to set up or is too slow
- The original depends on services independent of us (api client of the payment system)
- The original depends heavily on user input
- The original is not deterministic
In some cases, instead of mocks, you can do fake:
- Instead of a real database - an object in RAM
- Instead of a real SMTP client and mail server - mail in memory
At the same time, if at all possible, you need to cover with tests the original functions for working with the database and mail, because this is a critical code, but for this there are integration and end2end tests
In your example, it is quite possible to block the sending to the mail, as it is difficult to test.
Saving in the database can be replaced with a fake, for the sake of faster passing the test
. You can leave the original hash generation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question