5 ms·
Testing Without Mocks: A Pattern Language
- djur 4y agoThere's actually some good ideas in here. I wish it wasn't written in such a buzzword-heavy, consultant-y style. When advice includes so many Novel Proper Nouns I find myself checking my wallet. My main quibbles are that these "Nullables" are still test doubles, just implemented in a way with different tradeoffs than typical mocking frameworks. Also, spies are still helpful when you're checking for side effects. I'm not really seeing any alternative offered here for testing "does this code send 0, 1, or 500 emails".
- readthenotes1 4y agootoh, I worked with a guy who was so mock heavy that he actually wrote real mocks for hash table for each test. I worked with another guy who mocked out so much external behavior that he couldn't figure out why his stuff never worked, not doing the necessary work to ensure that his expectations of external behavior were actually still met ( if you're going to mock out external behavior, you need to add in tests that ensures your expectations are valid). There is a place for Mocks, but I have found the other varieties of test doubles to more useful...
- convolvatron 4y agowhat is the place for mocks?
- Tainnor 4y agoExternal systems, unexpected error cases (which by nature of being unexpected can't really be triggered in a "natural" way), very generic code (e.g. instrumentation frameworks), major architectural boundaries, ... I agree that most people over-mock, though.
- readthenotes1 4y agoExternal systems dependencies are better handled with stubs and fakes than mocks, in my experience.
- Tainnor 4y agoThat really depends on the case in question and on the particulars of the codebase. I wouldn't recommend mocking http libraries, database calls etc. - that usually leads to madness and impenetrable test setups. I would rather recommend to either use fake implementations (e.g. in-memory DB) or to only integration-test the boundaries of your interaction with the external system (that might or might not be hard to achieve). But I do like the pattern of wrapping calls to external APIs through a layer that I control - so that, for example, I may just write mailer.sendMessage(message) - and then that mailer interface seems like a good candidate for mocking.
- readthenotes1 4y agoIn my experience, they are the test double of last resort. I used them to verify behavior, not outcome (as that's what expectations do), e.g., did I really call this method only once?
- what-no-tests 4y agoIf I'm writing unit tests for #some_method, I'll mock anything that method calls outside of that method (so I can check how that method will respond to error conditions from calling those other methods). Unit tests != Integration tests, and the two must both exist otherwise I'll run into that situation where my unit tests work but the software doesn't.
- UglyToad 4y agoBut do you not find the problem is you now end up with tests that assume the existence of #some_method with the tests tightly coupled to the internal logic and flow of that method? If you decide to refactor, every part of the system now has one or more tests that break because they mimic or clone each method 1:1 rather than testing input and output.
- readthenotes1 4y agoExactly the problem the 2nd guy had
- what-no-tests 4y agoPerhaps, but if I refactor #some_method I only have to look in my unit tests where I describe #some_method and focus there. The integration tests should not have to be updated, since they only describe expected behavior -- unless the expected behavior must change as well. The coupling between unit tests and the methods they test is correct, IMO, because really how else are you supposed to test what #some_method would do when it tries to call #another_method but #another_method raises various different exceptions, or returns no results, or returns successfully? If the answer is "I only test happy paths" then good luck - you're not really testing anything.
- jdlshore 4y agoAuthor here. The way to test "does this code send 0, 1, or 500 emails" is the Output Tracking pattern: https://www.jamesshore.com/v2/projects/testing-without-mocks/testing-without-mocks#output-tracking https://www.jamesshore.com/v2/projects/testing-without-mocks... Thanks for the wallet!
- djur 4y agoThanks for the link and the original article. To me, OutputTracker looks a lot like a spy, except instead of verifying that the unit under test took a particular action you're instead verifying that it logged that it took an action. That would seem to create the risk of missing cases where the events emitted by code don't match its actual behavior.
- jdlshore 4y agoOutput tracking and spies are solving the same problem, but they do it in different ways. Spies record which methods are called. Output tracking records behavior that's otherwise invisible to callers (such as inserting something into a database). There's no risk of missing cases. The output tracking happens at the same semantic level as the rest of the code and is a binary "tracked / not tracked" type of thing. There's no behavior to match, and the code is tested anyway. Edit: By "no behavior to match," I mean that the thing doing the behavior is the thing tracking the behavior. The tracker is driven by events you emit when you perform a behavior.
- djur 4y agoI'm saying that if I have code like this, with payload = prepare_payload if verify_payload?(payload) mailer.deliver(payload) emitter.emit(:sent_the_email) end there is a risk that a later change to this code will make it so that the `mailer` and `emitter` are not guaranteed to be called together. I have seen this bug in production and I don't see how your approach catches it. I'm also not sure how I'm supposed to test for different desired values in `payload` here.
- 4y ago
- chociej 4y agoI feel that the writing style reinforced the well-thought-out consistency of the system. The information of value was all right there, so I didn't feel worried about getting a bill.
- viraptor 4y agoI'm not sure why this would be in the goals / positives. > Tools that automatically remove busywork, such as dependency-injection frameworks and auto-mocking frameworks, are not required. The examples are basically doing manual DI. You don't need more in this small case case, but if you're actually using specific implementations for test, why not help yourself by reducing that busywork? You can always fall back to manual parameter where needed even if you do use DI, so using one is typically not restricting you in any way.
- deleted 4y ago[deleted]
- thom 4y agoOnce you’ve replaced each infrastructure dependency with some form of test double (whatever you call it) that captures state, broad tests are no longer slow nor do they fail randomly so I’m not sure I understand why you’d ditch them. Ubiquitous narrow tests are brittle in the face of most refactorings whereas broad tests care about things your users care about and usually persist across those changes. I’d always prefer the latter, though I’m happy to have both. A codebase without broad tests (or without explicitly modelled use cases that are ‘sociable’ with a broad range of dependencies anyway) is unlikely to describe what it actually _does_ anywhere and sounds like a pain to reason about.
- jdlshore 4y agoAuthor here. What you’re describing is basically the same thing as sociable tests at the top of your system, which is part of what I'm recommending. You could stop there if you wanted. I like having narrow tests rather than broad tests, though, because it allows me to keep my tests localized. For example, in the simple example app, I have a Rot13 module with a bunch of edge cases. How does it handle upper-case letters, lower-case letters, numbers, symbols, etc. I could test that with broad tests, but doing that in a large system means that you end up with a combinatorial explosion of tests, or (more likely) hidden gaps in your tests. I find it easier to test my code thoroughly with narrow tests, which allows me to test higher-level code with the security of knowing that lower-level code Just Works(tm) and doesn't need further testing. I haven't found narrow sociable tests to be brittle in the face of refactorings, at least not when using the patterns I describe. That's a big motivation for the pattern language—to make refactoring easy, even big architectural refactorings—and that's turned out to be true in practice.
- vikinghckr 4y agoHi, I really enjoyed the piece! How much to test at each layer of abstraction has always been something that's bugged me. This article provides a nice strategy. I still have questions about a few scenarios though. Let's say, I have two classes like this: class KeyValueStore { int64 Get(Key key); }; class CachingKeyValueStore { CachingKeyValueStore(const KeyValueStore& wrapped); int64 Get(Key key); } Here, the `CachingKeyValueStore` class is a wrapper around the `KeyValueStore` class, and its purpose is to simply maintain an in-memory cache (instead of RPC calls or Database calls). How would you unit test the `CachingKeyValueStore` class? So far, using Mocks have been my only strategy, because behavior-wise, both classes have the exact same outputs for the same inputs.
- mgaunard 4y agoJust a lot of weird words to describe plain dependency injection techniques.
- BoiledCabbage 4y agoDo you have names for these various techniques? Are they defined somewhere?
- mgaunard 4y agoIt's just called dependency injection. Somehow he invents nonsensical buzzwords to describe every line of code.
- Terretta 4y agobuzzword: stock phrases that have become nonsense through endless repetition So if he invented it, it isn't stock, and if it's annoying for its novelty it's not endlessly repeated in the industry. Probably you want the word lingo, not buzzword: lingo: [noun] strange or incomprehensible language or speech: such as. a foreign language. the special vocabulary of a particular field of interest. language characteristic of an individual.
- BoiledCabbage 4y agoSo it sounds like there is a sub-classification of a collection of techniques, you don't have names for them and they aren't defined anywhere. Sounds like someone should name them and write up their definitions somewhere.
- revskill 4y agoTest to me is a tool for debugging. Mock is at least useless to me. Use real mock instead by introduce real dependency, but with local effects.
- deleted 4y ago[deleted]
- hinkley 4y agoPure functions are great for testing. I keep iterating back to mostly functional cores.
- pharmakom 4y agoDefunctionalisation is the most powerful design pattern I have found for business backend programming.
- charles_f 4y ago> Their tests are reliable and fast, but they tend to “lock in” implementation, making refactoring difficult Try and make a refactoring for something that has no unit tests, or upgrade a db for tests that directly validate the values in the db. I'm not sure I get where that claim that mocks lock-in implementation is coming from, if anything they make it less locked in.
- Ygg2 4y agoI think the big issue is. Are you writing a lib or an app? In library you don't need to mock. Library is supposed to be agnostic. In app there are many layers. You kinda need to mock them all, otherwise your app can't be tested. And then you have the problem that minor changes turn your tests red. So mocking is most useful in the place it has almost no impact. https://youtu.be/VDfX44fZoMc https://youtu.be/VDfX44fZoMc
- Ygg2 4y agoClarification of link: one solutions to unit tests is to write even more unit test, with some contract tests, etc. Another approach is to treat integration test as a unit test.
- deleted 4y ago[deleted]
- elboru 4y agoI think one of the biggest issues is the definitions we use. Some developers would define mock in the wide sense, as any kind of double to replace a dependency. Other developers have a narrower definition, as doubles that verify interactions with the dependency (interaction testing https://testing.googleblog.com/2013/03/testing-on-toilet-testing-state-vs.html https://testing.googleblog.com/2013/03/testing-on-toilet-tes...). In this case, the author mentions mocks and spies, therefore he's referring to "interaction testing". In other words, tests that verify that the dependency was called in the "right" way. If you own those dependencies, and later you refactor them you'll also need to refactor any test that used "interaction testing". Refactoring becomes a tedious and sometimes difficult task. If by mock, you simply mean code (written by you or by a "Mock" library) that replaces a dependency to get the right data inside the SUT for the test, but that it's not attached to the dependency implementation, then most of the issues are gone.
- dang 4y agoRelated: Testing Without Mocks: A Pattern Language (2018) - https://news.ycombinator.com/item?id=30565918 https://news.ycombinator.com/item?id=30565918 - March 2022 (28 comments) Testing Without Mocks: A Pattern Language - https://news.ycombinator.com/item?id=16943876 https://news.ycombinator.com/item?id=16943876 - April 2018 (12 comments)
- DotaFan 4y agoYear ago we switched from testing with Mocks to testing with Doubles/Fakes, and it sped up our testing quite significantly, we write, maintain and run tests faster.
- SeriousM 4y agoThe blog post is quite interesting to read! One tradeoff I found is that it doesn't work with dependency injection. I use c# for about 20 years and DI is the best, IMHO, that was adapted my Microsoft not too long ago. When we're writing code against external systems we define wrappers. During test startup we replace the real implementation DI registration with a Moq (usually strict mode) or a concrete testable implementation. This way we get the nullable-instance into the dependency graph. This is certainly not the fastest way (measured against thousandsof tests), but it works for the team very well.
- jdlshore 4y agoI'm not sure what you're getting at. Look at the examples. They all use dependency injection. Maybe you meant dependency injection frameworks? That's not true either; it works exactly the same way as any other approach: the DI framework injects production objects, and the tests inject their own test objects.
- SeriousM 4y agoThank you for your comment, maybe I wasn't clear with my statement. I referred to dependency inversion (and therefore also frameworks of it). When using DI you have no possibility to define ".asNullable" as you like from case to case, instead a framework is deciding for you. By using DI during tests it's therefore impossible to use the advertised "nullable" pattern as described. Looking at the examples all of the code does not use dependency inversion. https://en.m.wikipedia.org/wiki/Dependency_inversion_principle https://en.m.wikipedia.org/wiki/Dependency_inversion_princip...
- jdlshore 4y agoI know what the dependency inversion principle is. I think there's some fundamental misunderstanding here, because dependency inversion is a design pattern, not a framework, and there's nothing about it that prevents you from using Nullables in your tests. Regardless of whether you're using dependency inversion, or dependency injection, your class under test can be programmed with the following constructor: class MyClass { private MyDependency myDependency; MyClass(MyDependency myDependency) { this.myDependency = myDependency; } // rest of code } This is the fundamental dependency injection pattern. (Well, there's other ways to do it, but this is most common.) No matter what DI framework you're using, you probably have constructors that look like this. If you do, you can use Nullables. And if you don't, all you need to do is add them. It's possible that your DI framework is generating these constructors for you automatically, in which case (1) ewwww, and (2) if you dig into your framework's documentation, there's probably a way to make it work with Nullables.
- ddyevf635372 4y agoAre you a mockist or a classicist? ;) A few useful article in this topic: - https://martinfowler.com/articles/mocksArentStubs.html https://martinfowler.com/articles/mocksArentStubs.html - http://www.captaindebug.com/2011/01/are-you-mockist-or-classicist.html http://www.captaindebug.com/2011/01/are-you-mockist-or-class...
- luisapic 4y ago[flagged]
- pugworthy 4y agoSomeone asked the development team how to mock Scala a few years back. The answers were amusing given the "Java vs Scala" wars going on with the team at that time.
- u801e 4y agoI typically write tests and code in a way that I test the functional core of the code without testing the imperative shell part of it (at least for the unit tests). But we also test our code by provisioning a local VM that not only deploys the code as it would be deployed on a production instance; it also installs and configures dependencies for the code. For example, installing a DB store and populating it with test data. Our integration/functional tests will then run queries against the code and check whether the DB store was updated as expected, we got the appropriate API response from the call to it, and whether we get expected output from the logs. This way, we're not using mocks that may not be updated depending on the state of the production environment. We're using the same code that we use to deploy services in production, but just putting anything on the same VM rather than having them on different machines accessible through a separate endpoint.
- japanman425 4y agoSo e2e tests then?
- newbieuser 4y agoIt's an interesting idea to write the app based on the tests instead of writing the test by the app. I don't think it will be very healthy for the overall application, but it's worth a try. Testing with real dependencies without using mock seems better overall, but this brings with it quite a few problems.
- seveibar 4y agoI love outside-in testing, where tests are essentially any bug reported by a customer with fixturing of the db and api calls to an instance of the application and all dependencies are faked or doubled. At Seam, we use fakes for the 20+ IoT integrations we support. The fakes/doubles are a significant amount of work but 10x maintainability and imo make development more fun because you have a reference system and a lot of freedom in fixturing and testing. I use unit tests sparingly, where the combinatorial explosion is prohibitive for standing up instances or the logic has a lot of careful edge cases. We don’t really have performance issues because outside-in testing is horizontally scalable, at Seam our ci may have 16 or so parallel test runners/PR. I saw this pattern of horizontally scaling tests being used on the NextJS repo as well, they would fixture the filesystem for a NextJS project then allow you to interact with the running application, and IIRC they had thousands of tests like this. I think it simplifies logic to couple the logic to the database + http calls directly rather than introduce layers of infrastructure abstraction. It can vary depending on application, but especially if you’re using query builders I doubt it’s worth it to create the infrastructure layer. Edit: In relation to the article, I’m mostly disagreeing with “keeping tests narrow” and the infrastructure layer, but in agreement with many other concepts such as the author’s Nullable double concept, which simplifies creating doubles.
- theteapot 4y agoOnly read the intro. I can't read any more, because I'm super confused by this piece of writing. But you asked for feedback, so (limited to intro): > Folks in the know use mocks and spies (I say “mocks” for short in this article) to write isolated interaction-based tests. Their tests are reliable and fast, but they tend to “lock in” implementation ... Depends on how you implement it. Mock almost by definition does not lock in implementation as it is a reimplementation of an interface. Spies yeah OK, but depends on how you use. You should probably distinguish between Mock and Spy or state why you conclude they lock in implementation. > Bad tests are a sign of bad design, so some people use techniques such as Hexagonal Architecture and functional core, imperative shell to separate logic from infrastructure. You could have said: "Bad tests are a sign of bad design, so some people improve there design.". Genius move. Hexagonal Architecture has nothing to do with it, it's wild conjecture that Hexagonal Architecture is going to improve anything. > (Infrastructure is code that involves external systems or state.) No, it isn't. Maybe you confusing Infrastructure-as-code with Infrastructure-is-code. > It fixes the problem... for logic. What problem? If we trust you, we hypothetically improved the design and architecture. Test can still be bad. I would drop this whole "Bad tests are a sign of bad design ..." paragraph. I mean why the heck are we talking about Hexagonal Architecture here. > The patterns combine sociable, state-based tests with a novel infrastructure technique called “Nullables.” At first glance, Nullables look like test doubles, but they're actually production code with an “off” switch. Man, just because you comingle you mock with your actual code - which seems very anti SOLID - doesn't make the thing not a test-double. It's still a test double, just a weirdly coupled one. > The rest of the article goes into detail. Don’t be intimidated by its size. It’s broken up into bite-sized pieces with lots of code examples. The rest of the article is like a book that has nothing to do with the title of the article? You should explain what all that is or put it somewhere else. Hope that helps.