Answer the question
In order to leave comments, you need to log in
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'
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question