2 ms·
Because people hear “unit tests” and “integration test” and “behavior test” and bend over backwards to start DI and mock every single little thing and be very c
by vlovich123 5y ago
Because people hear “unit tests” and “integration test” and “behavior test” and bend over backwards to start DI and mock every single little thing and be very careful about organizing things in that way, which is a huge anti pattern in my experience. You should DI/mock only when you have no other choice (eg you need to corrupt the data returned by an I/O call to test some corner condition). Generally, the less DI/mocking/supporting code just for testing purposes you have, the simpler and more testable (ironically) your codebase actually is. The reason is that you’re actually testing the behavior of each function in a wider variety of test cases than just the ones written for that one function. You use fuzzers or property tests to generate a wide variety of test cases. The purists will argue that this makes tests brittle because changing a core routing can suddenly cause many tests to fail/ need updating. In practice I’ve observed that such updates are typically trivial and mechanical while with mocks you end up doing the same thing anyway (change an interface and suddenly you have a bunch of mocks that need updating anyway).
Mocks and DI can be useful. Don’t get me wrong. But use them sparingly and judiciously when they’re the right tool for the job. Recognize that they’re usually not.
- the_gipsy 5y agoVery insightful. I've found the same about "using DI only to force errors / corrupt data on IO".
- throwaway858 5y agoAgreed. If you have a function that executes an SQL query then your unit test(s) of this function should also execute the query. Otherwise, what exactly are you testing? Just because the database runs as a separate process does not mean that this is an "integration" test. Imagine if you had a function that did some floating point math and then you wanted to test it and I told you "hang on, this function actually utilizes the FPU which is a separate piece of hardware and therefore if you test it then you're doing an integration test.. if you want a proper unit test then you must mock the FPU and use dependency injection". Madness. Executing a database query is no different from executing a CPU instruction or calling a library function.