this post was submitted on 28 Jun 2023
515 points (97.2% liked)
Programmer Humor
19471 readers
1516 users here now
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
Rules
- Keep content in english
- No advertisements
- Posts must be related to programming or programmer topics
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Here's my take. In order to be able to write meaningful unit tests the code should be structured in a certain way, with very modular, decoupled units, dependency injection, favoring composition and polymorphism over inheritance and so on.
If you manage to write your code this way it will be an objective advantage that will benefit the project even if you don't write a single unit test. But it does make unit tests much easier to write, so presumably you'll end up with more tests than otherwise.
IMO teams should prioritize this way of writing code over high test coverage of non-modular code. Unit tests for deeply-coupled code are a nightmare to write and maintain and are usually mostly meaningless too.
I really hate the projects I work on where they've overtested to the point of meaninglessness. Like every single class has a full suite of tests mocking every single dependency and it's impossible to look at it without breaking 50 test cases.
Similarly I hate the projects with no tests because I can't change anything and be sure I've not broken some use-case I didn't think about.
Much prefer the middle ground with modular, loosely coupled code and just enough tests to cover all the use cases without needing to mock every single little thing. It should be possible to refactor without breaking tests.
For real. I have been using DI to only mock infra and external services while keeping the actual code unmocked, and using an in memory db (we use Dynamodb so that's easy) for testing. I write tests only at the interface level, send data in, mock infra, external services, and then assert side effects. Found this to work very well for now, especially for Lambdas which we have quite a lot of.
Whenever we encounter a bug, we ensure that that case is captured in a unit test as well, but priority on integration tests.
This. Just thinking about how you would test something leads to better code, at least in my experience.