> Do whatever that will increase confidence in code and testability.
Heh. I've long felt a need to write a blog post touching this very idea, but have been too lazy to.
I think a lot of people (including younger me) would dive right in to things like unit tests without too much thought. Now I focus on:
- What should we test? (Think about the feature you are adding and why - what aspects need to work?)
- Why? should we test it?
- Should we test it? (really the same as above). Common to see junior folks end up testing 3rd party libraries.
- How should we test it? Mocks? Unit tests? Integration tests? Something else?
- Is it even testable in an automated fashion? If not, ponder over what makes it hard to test. Does that need to be rectified?
- How can we be sure we're testing what we think we are? Extremely common to see people write tests that appear to pass, but are testing the wrong thing (buggy test). It's very rare that I see a colleague intentionally introduce a bug in the feature to see if the expected test will fail.
- What is the cost of this feature having a bug? If it's very costly, you may want to have multiple types of tests, and possibly even a human testing it each release. If the cost is almost zero, and you won't need to fix it quickly if a customer reports it, and it's hard to write an automated test for it - just skip it. If this mentality bothers you, know that this is recommended by the ISO standard for SW in cars - even if a bug can end up in loss of life, if you can show it's extremely unlikely, you are conformant if you don't test it.
You should first answer these questions, and they will then guide you into whether to write unit tests, or E2E tests, or something in between. I generally find that people who dive into testing without answering the above write crappy tests (buggy, pointless, etc). Answering these can lead to better mocks (or a decision not to rely on mocks).
In summary, step back and forget everything you've learned about testing before answering these questions. Pretend you don't know the difference between unit tests, integration tests, etc. You've written (or plan to write) a feature.[1] What would you like to test in an automated fashion, and how can you do it? Feel free to use any tool that works for your project.
[1] You're not writing code. You're writing a feature.