←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. 01HNNWZ0MV43FF ◴[] No.45951112[source]
"sans-I/O" is one term for that style. I like it a lot but it's not a free lunch.
replies(2): >>45952313 #>>45952597 #
2. sunrunner ◴[] No.45952313[source]
I always liked the phrase 'Hoist your I/O' [1] but yes, you can only hoist it up so many times until its outside of your application completely (making it completely pure, and now someone else's responsibility).

[1] https://www.youtube.com/watch?v=PBQN62oUnN8

3. Vinnl ◴[] No.45952597[source]
Or "functional core, imperative shell".