←back to thread

67 points ingve | 3 comments | | HN request time: 0.001s | source
Show context
BoiledCabbage ◴[] No.45950554[source]
The mock discussion still misses the real solution, which is to refactor the code so that you have a function that simple reads the file and returns json that is essentially a wrapper around open and doesn't need to be tested.

Then have your main function take in that json as a parameter (or class wrapping that json).

Then your code becomes the ideal code. Stateless and with no interaction with the outside world. Then it's trivial to test just like and other function that is simple inputs translated outputs (ie pure).

Every time you see the need for a mock, you're first thought should be "how can I take the 90% or 95% of this function that is pure and pull it out, and separate the impure portion (side effects and/or stateful) that now has almost no logic or complexity left in it and push it to the boundary of my codebase?"

Then the complex pure part you test the heck out of, and the stateful/side effectful impure part becomes barely a wrapper over system APIs.

replies(10): >>45950831 #>>45950929 #>>45951112 #>>45952380 #>>45952963 #>>45954934 #>>45958404 #>>45958469 #>>45960148 #>>45960154 #
1. wry_discontent ◴[] No.45954934[source]
This sounds great until one of your other functions calls that function.

You're just describing dependency injection, but if you say that, people won't want to listen cause doing that all the time sucks.

replies(1): >>45959914 #
2. bccdee ◴[] No.45959914[source]
Dependency injection frameworks can be a pain, but basic dependency injection (e.g. pass a DB handle to anything that needs the DB) is a must. What's the alternative? Having everyone independently create their own DB connections?
replies(1): >>45967955 #
3. wry_discontent ◴[] No.45967955[source]
It's my preference to a point. I think you can over-do it. I've worked in systems that didn't use it and worked just fine. I would bet most folks err on the side of too little, unless they have some kind of framework doing the heavy lifting.