3 ms·
How do you avoid external dependencies in this situation? If you're only testing the public interface, then you have to expose some kind of public dependency in
by jniedrauer 6y ago
How do you avoid external dependencies in this situation? If you're only testing the public interface, then you have to expose some kind of public dependency injection pattern. Now you've introduced a level of indirection into the production code specifically to make testing easier. This feels like an antipattern.
It's how I do it, but I'm not satisfied with it. It makes the code harder to read, I sometimes miss bugs because my injected mocks don't handle an edge case correctly, and the effort of maintaining the mocks themselves is non-trivial.
- Tainnor 6y agoI don't agree that dependency injection is necessarily bad, but if you really want to avoid it/mocking, there are also other ways, i.e. structuring your code into pure and impure parts, only unit testing the pure stuff and relying on integration tests for the "wiring".
- UK-Al05 6y agoFor most web applications I barely use mocks except on the edges. For mocking out boundries like calling http service I need to call, I do the following. I will write an integration test against the real object representing API. These tests will test the real thing. I will then run those same tests against a fake object I've created which represents the API in tests. Your fake and real objects are now guaranteed to work the same based on the properties you test. I can now use the fake object in tests with a higher degree of confidence. You can do the same thing around data access objects.
- Tainnor 6y agoI agree, fake objects are a good alternative to mocks especially for complicated interfaces (databases, external services, etc.). But they require more setup, which is why I still think mocks can be useful in some situations.
- UK-Al05 6y agoThey can require more setup in that you have to write an object to represent the thing. They require less setup in that mocks require tons visual noise in setting them inside the test. Where as a fake will just be created with a standard constructor. I hate a lot of mocking I see in real code. They go over board with the mocking and the test is 80% mock setup. Making it hard to see the real purpose of the test. Tests should be short, simple, to the point, and easy to read. When most of the test is setting up a mock, you've lost that. But there not too bad if it's a very simple one line setup. Which is how they should be used. But that would not tell you that if you passed a null object into the real thing it would crash. Where as fake, with the tests will.
- Tainnor 6y agoI think it really depends. If you keep the number of collaborators in a class small and your interfaces are well designed mocking is ok (and really just a limited form of a fake). But sure, many people don't do that.