3 ms·
That is one of the big benefits I have found from writing code while planning to write unit tests for it (even if you don't write all of them). You will general
by saynay 5y ago
That is one of the big benefits I have found from writing code while planning to write unit tests for it (even if you don't write all of them). You will generally avoid patterns that will require a lot of mocks to test, which generally make that code easier to refactor and reason about. If you are able to make big chunks of your code into "pure" functions, they are now really easy to test.
- rectang 5y agoA classic approach is that if you have to make some complicated API call with a bunch of arguments, you can put all the logic wrangling the arguments into a pure helper function and unit test the helper.
- mring33621 5y agoAgree. I use strategy pattern with Java functional interfaces to avoid using magic mocking frameworks. That way, my mocks are just trivial impls of the plugin parts.
- geysersam 5y agoHow do you accomplish that? I often end up in a situation where mocks are needed (like in the article).
- saynay 5y agoOften times, you will have chunks of code that are either creating input for what would go into an interface/mock, or handling the output of it. You could pull those bits, even if they are relatively simple (maybe only a few lines, and only used in that one spot), and extract those out to a pure function to sidestep the mock. Sometimes you can't really avoid it. In those cases, I would judge how much of the effort is testing your code, and how much is testing your ability to write mocks. Unless it is a really important functionality, or something complex enough that it would be easy to get wrong, I wouldn't bother with most tests that need extensive mocking. Instead handle those later with integration / e2e tests.
- atx42 5y agoAlso agree. I've seen code so mocked it was dubious that it could be testing anything, accurately at least.
- 8note 5y agoSetting up sample data is the biggest pain for mocking in my experience. But it's true however you're testing.