13 ms·
Good lord. Why integration tests? I think the biggest thing you can do to write more integration tests is to just stop mocking so much stuff. Okay. The
by hinkley 9y ago
Good lord. Why integration tests?
I think the biggest thing you can do to write more integration tests is to just stop mocking so much stuff.
Okay. The biggest problem I see with people trying to write unit tests is that they don’t want to change how they write code. They just want tests for it. It’s like watching an OO person try their hardest to write OO code in a functional language.
So they try to write E2E tests which work for about 5 or 6 quarters and then fall apart like a cheap bookcase. If you can find a new job before then, you never have to learn to write good tests!
I agree with the author that the trick is to stop using mocks all the time, but you don’t have to write integration tests to get rid of mocks. You have to write better code.
Usually if I have a unit test with more than one mock it’s bcause I’m too invested in the current shape of the code and I need to cleave the function in two, or change the structure of he question asked (eg, remake two methods into two other methods).
Almost always when I accept that the code is wrong, I end up with clearer code and easier tests.
Unit tests run faster, are written faster, and not only can they be fixed faster, they can be deleted and rewritten if the requirements change. The most painful thing to watch by far is someone spending hours trying to recycle an old test because they spent 3 hours on it last time and they’ll be damned if they’re going to just delete it now.
- jasim 9y agoNo true Scotsman. You might be speaking about those cases where people write large god classes, pervasively side-effectful code, zero API design, and a general lack of pure abstractions - then their tests would equally be bad. Tests are code, so one's ability to design programs would reflect on their tests and vice versa. But a reasonable programmer who cares enough about what they do can still end up with a brittle test suite because of other factors. Unit tests written in a dynamic language is a major drag on refactoring. It is not so much that we test the internals of the system or get tied up with the shape of code internal to an object. Even if you follow Sandi Metz's wonderful guidelines around testing: i) do not test internals, ii) test incoming queries by asserting on their return value, iii) test incoming commands by asserting on their side effects, iv) mock outgoing commands, and v) stub outgoing queries, you end up with a brittle test suite that is hard to refactor thanks to connascence. Whenever you refactor your names, or shuffle the hierarchy of your domain elements, you are now left with a thankless chore of hunting and pecking your unit tests and making them reflect the new reality of your code. Here integration tests help you know that your system still works end to end, and unit tests simply remain that one thing that refuses to budge until you pay it its respects. Unit testing complex views is still a hard problem. There are no well-defined stable "units" to speak of in an ever changing HTML UI. We have snapshot tests, we try to extract simple components on whom we can assert presence/absence of data, and we have integration tests that blindly railroads over everything and make sure the damn thing worked. But in a different context unit testing is the one true answer. If your system is statically typed (say in Haskell or OCaml), and your functions are pure and compositional, you don't so much worry about mocking and stubbing. You can make simple assertions on pure functions and as the granularity of your functions increase, they end up covering more parts of your system and get closer to an integration test. Static types form another sort of guarantee, the most basic one being that it takes a class of bugs away in form of undefined data types, the system going into invalid states, and of course the clerical mistake of named connascence. We often abuse unit tests in dynamic languages to cover these scenarios, leading to huge test suites with very brittle tests. I think it is important to call out that the value of unit tests are still contextual - "it depends" like everything in the world, and despite our best efforts, they can become hard to refactor. There is a case to be made for writing integration tests because they deliver more business value at a cheaper price than a pervasive set of unit tests when dealing with a highly effectful dynamic system. This lets us also think about other forms of testing like generative testing and snapshot testing that come to the same problem from different angles.
- AlexCoventry 9y agoThis is a great comment, not sure why it's at the bottom of the thread. Gets to the core values underlying the main religious beliefs about testing.
- ntrepid8 9y agoYup, agree. Depending if you are working with a good static type system or with a dynamic language the value of unit tests can vary. When working with dynamic languages I always end up writing a bunch of unit tests and a bunch of integration tests. I've experimented some with type hinting and static analysis in some dynamic languages but it's not the same as having the compiler make guarantees.
- josteink 9y agoI work in a company where quite a few of the developers simply are incapable of writing anything but integration-tests. The reason? They don’t “believe” in unit-tests. They don’t think unit-testing “works in the real world”. They absolutely fail to accept that they need to write their code differently for automated testing to work well. How do you change such a mindset?
- hvidgaard 9y agoI doubt that you can. There was a study a while back, and I apologize in advance because I do not have a link, that showed projects written with unittests took significantly longer to reach the market, but with significantly less bugs. However, overall time spend on the code was less. So conclusion was that unittests are a commitment to a long term goal of minimizing developer time, and the tradeoff is that it takes longer for the first version to be done. That is, as far as I know, the only tangible evidence that unittests are good unless you need to get something out the door quickly (which sadly is most of it). I'd argue that is not the main benefit of unittesting however. That is the way code is structured, and especially how dependencies are explicit, e.g. injected with constructor arguments.
- chewbacha 9y agoMan, I really want to read that study!
- hinkley 9y agoThat parallels my experiences. I got tired really early on with projects that ground to a halt because of brittleness and a lot of my focus is on building skill and confidence so that version 3 is no harder to ship than version 2 was. Every team I’ve left on good terms was more effective when I left than when I got there. The ones that fought me the whole way frustrate me and it shows.
- alien_at_work 9y agoWas this the microsoft study? I think it was a breakdown of their delivery of Vista?
- davidjnelson 9y agoFunctional, integration, and unit are all different types of tests. He's saying write more integration tests, not more functional tests. For algorithms, I love how I can refactor the implementation and still have 100% confidence in the result if it tests sample input against expected output.
- skybrian 9y agoThis sort of discussion often gets confused because people have different ideas about what integration tests are and therefore talk past each other. I generally avoid the term altogether and recommend testing stable API's (which are often public) and avoiding testing internal API's that are more likely to change. This assumes you have a stable API, but that's true of most libraries.
- betageek 9y agoExactly - Integration tests !== E2E tests
- profalseidol 9y agoMartin Fowler solves this by introducing: SubcutaneousTest https://martinfowler.com/bliki/SubcutaneousTest.html https://martinfowler.com/bliki/SubcutaneousTest.html
- MartinCron 9y agoCatchy.
- Lord_Zero 9y agoI think we are discussing what it means to test a stable API or an internal API. Not just testing them in general. We're talking about making architecture decisions on your code in the interest of test-ability. Regardless of the visibility of your API you will still need to unit test the logic will you not? Do you test your controllers and then the response from your service layer? Is all your logic in your actions?
- olavk 9y ago> Good lord. Why integration tests? Because they can find bugs and errors which unit tests cannot.
- fnord123 9y agoThis is true. Areas where I have full unit test coverage tend not to have any bugs. What a waste of time to have written all these tests!
- kelnos 9y agoThe problem is that it's almost always possible to achieve a similar or identical number of bugs with lower test coverage, and every test you write has a maintenance cost. In my experience, the vast majority of test failures (after I've made a code change) end up being issues with the tests themselves, and not with the code change. If you're testing obviously-correct code, that's just more that can spuriously break later and require time and effort to fix and maintain.
- Matumio 9y agoYeah, assuming you think it's not a bug when the backend API that you're mocking is accidentally removed or changes its response slightly.
- fnord123 9y agoYou seem to be implying that I prefer all unit tests and no integration or system tests. Far from it. A system test catches the backend API issue. A unit test can demonstrate that my component degrades gracefully if the backend API is not available (because I used a mock to provoke a timeout response).
- bpicolo 9y agoThere are plenty of systems out there that can't degrade particularly gracefully. That said, the big issue with unit tests is they don't test the glue which is where a lot of issues happen. In languages with strong type systems, this is less of an issue. Unit tests are great when you actually have complex logic with relevant corner cases, but when you're building web apps, 95%+ of your code is just boilerplate data munging
- jasonkester 9y agopeople ... don’t want to change how they write code. They just want tests for it Have you considered the possibility that those people are right? That's a reasonable conclusion to make if you are seeing lots of otherwise smart people that share an opinion that disagrees with yours. There are lots of valid reasons to change the style in which you write code. In my mind, fitting somebody's fad testing scheme is not one of them. Here's a second opinion from a guy who also likes tests, but doesn't think it's a good idea to structure your whole codebase just to accommodate them: http://david.heinemeierhansson.com/2014/test-induced-design-damage.html http://david.heinemeierhansson.com/2014/test-induced-design-...
- TeMPOraL 9y agoI strongly agree with that, too. My current, experience-born belief is that if the only reason for introducing some architectural pattern is to accommodate testing better, the change is wrong and will likely hurt the code quality. Yes, you need to concede a little bit to allow for test points, but turning your code inside-out to have it go through three layers of indirection so that the middle one can be mocked easily? That's just stupid.
- afarrell 9y agoyea, you should be changing code style to increase modularity in a way that is conceptually coherent in terms of what is easy to hold in your head. Increased testability should fall out of that because you can think through "What invariant should hold true about X under conditions/inputs Y1...Y4?"
- hinkley 9y agoCode you can hold in your head usually has a smaller surface area. Fewer moving parts equals easier testing.
- hacker_9 9y agoUsually splitting out into interfaces is done in static languages as that's the best type-safe way to do things. It's not a fad, it's been like that since the beginning.
- TeMPOraL 9y ago> The biggest problem I see with people trying to write unit tests is that they don’t want to change how they write code. They just want tests for it. It’s like watching an OO person try their hardest to write OO code in a functional language. The biggest problem I see with people advocating for tests and employing TDD is that they do change how they write code to accommodate tests. This leads to inclusion of lots of unnecessary abstraction and boilerplate patterns that make code less readable and more bug-prone. OO world has spawned numerous non-solutions to turn your code inside-out so that it's easier to mock things, at the expense of code quality itself. That said, if you go for functional style in OOP, i.e. shoving as much as you can into static helper functions and most of the rest into dumb private stateless functions, you suddenly gain both a clean architecture and lots of test points to use in unit tests. So you can have testable code, but you have to chill out with the OOP thing a bit.
- positivecomment 9y ago> as much as you can into static helper functions and most of the rest into dumb private stateless functions In our work we use C# and it is very hard, even next to impossible to make a static class pass a code review - given it's not for extension methods (which I hate... why not be explicit about the first parameter and stop acting as a part of the class </rant>). They just tell us to use IoC and move to the next point. I honestly don't know why. Our IoC library can treat a dependency as static or singleton, but those are also discouraged. Once I had a static class named GraphRequestHelpers* and the reviewer got really negative, FSM knows why. She told me that we need IoC to make everything testable and "Helper" in the name is a code-smell. Sounds cargo-culting to me but I have only 6 years of experience so who I am to know. * Now we have RequestExtensions and everything is apparently perfect.
- crdoconnor 9y ago>Okay. The biggest problem I see with people trying to write unit tests is that they don’t want to change how they write code. They just want tests for it. It’s like watching an OO person try their hardest to write OO code in a functional language. I've seen what happens when a developer tries to abstract away a database in a database driven app so it can be "better unit tested". It's a goddamn mess. If your app relies heavily on using a database, your app naturally integrates with a database then it makes no sense to test without it. You are intentionally avoiding testing in a way that will pick up bugs. >Unit tests run faster, are written faster Unit tests test less realistically. That means they don't catch bugs integration tests do. They also often take longer to write and are more tightly coupled. How coding this way came to be seen as a best practice is beyond me. Tight coupling and premature optimization is usually seen as bad practice in other areas.
- piaste 9y ago> If your app relies heavily on using a database, your app naturally integrates with a database then it makes no sense to test without it. You are intentionally avoiding testing in a way that will pick up bugs. Also, with Docker it's now actually feasible to automatically test against a real database at a reasonable speed. A Postgres container spins up in a couple of seconds, a SQL Server one in a little over four.
- crdoconnor 9y agoThat has nothing to do with docker, really. I run postgres standalone on my laptop and it starts in < 1 second.
- GordonS 9y agoI guess they meant so your tests can start with a blank or reproducible state. But you can of course achieve the same by running a script before your tests start. There are also some frameworks for doing this sort of thing too, such as Fixie for .NET
- 9y ago
- sbergot 9y agoIn some situations unit tests with lots of mocks will bring a negative value. Imagine a situation where you want to refactor a big piece of code with many dependencies but you don't want to change its public interface. If you mock everything, when you refactor, the test will break because the dependency structure will change, and the mocks are no longer relevant to the new implementation. You have to rewrite the tests. You did twice the testing work and more importantly you get absolutely no proctection against regressions because the tests for the 2 versions are not the same. If you build integration tests, they can remain the same. Less work and actual protection for your refactor.
- saas_co_de 9y agoVery good point.
- sitkack 9y agoTesting internals forces future programmers of the codebase to maintain those invariants. All code is a liability.
- hinkley 9y agoNot in my experience. Convincing people to delete tests that only assert one invariant when the business changes its mind is easy. It’s the ones that have residual value after removing one invariant that trap people into spinning their wheels.
- profalseidol 9y agoI agree with this. Although, if you offshore development here in the third-world where internet gets slower everyday. Running an integration test that queries to Amazon RDB can take forever. I hope this issue gets a spotlight and be noted that integration tests in third world countries is very very slow. And this high cost should be included in the estimates. To give you an idea, here it takes AT LEAST 5 seconds to load a page from the amazon console. Lol, even the software companies owned by the ISPs/Telco here complains that their access to AWS is super slow. They said that bad routing is the main issue and for some reason the ISP isn't doing something about it.
- pjmlp 9y agoBecause there isn't proper way to write unit tests for GUIs for example. They can only test parts of its behavior, not everything, and are too brittle to any simple UI/UX change.
- mbrock 9y agoWhy not just mock the UI drawing library? (I find this a very interesting question.)
- pjmlp 9y agoBecause you would be implementing a 100% of the UI features and still cannot prove if it meets the UI/UX design specs.
- mbrock 9y agoI think a lot of that is just the poverty of UI APIs and especially the imperative drawing paradigm. There's no reason in principle why we can't programmatically verify that the basics of the UI spec are fulfilled. If the whole UI layer is just impossible to verify then if we're at all serious about correctness then we should (hyperbolically) stop making UIs until we figure it out.
- hinkley 9y agoI can’t help but think this is because nobody writes testable GUI frameworks. You can’t build a castle on a swamp, unless you’re Monty Python.
- demonshalo 9y ago> The biggest problem I see with people trying to write unit tests is that they don’t want to change how they write code. It’s like watching an OO person try their hardest to write OO code in a functional language. <rant> I personally hate javascript with the burning passion of a thousand suns. I just can't stand it. I can't stand the syntax, the philosophy, the package manager, the idea of "lets not worry about how X work just do an include and npm install", the abyss that is the error system, the person who considered 'undefined' to be a good thing to implement, the NaN that has nothing to do with numbers but everything to do with type casting when there is no actual type system, the lack of a good standard library, the fragmentation and slow progression of the language, the callback hell, the coercive nature of it's operators when you don't expect them to, the 6000 ways you can make an "object" that is not really an object, the confused terminology that goes against every other agreed-upon language, the myriads of outdated tutorials that lead developers to copy/paste code that stopped working 10 years ago, the notion that javascript is sexy and ES6 fixed it, the fact that you (whoever reads this) think you fixed it, the godawful bloated frameworks, the fact that I need 14000 dependencies to run a simple project because every 2 lines require their own implementation of a github repo so that the developer can boast about his cool profile, and most of all I hate the person who thought it would be a good idea to take this mess and put it server side. </rant> I can put almost all of that aside and work through threw whatever is thrown at me. However, what I can't ignore is when a language is deceptive by nature. Ex. Javasript uses the term "object" to describe something that isn't an object in the traditional sense. Hence when an OO person tries to write OO code in said language they end up getting virtually molested by whoever designed said functionality mainly because the OO person expects things to work in a certain way when they don't due to naming. The problem is not them not adapting and changing how they write code; the problem is actually the language itself being designed by retarded monkeys who confuse terminology and at the same time don't communicate the reasoning behind their decision making. Hence what you get is someone like myself who spends hours pulling his hair out trying to figure out why there is nothing similar to an isset() function in the standard library or why '2 == [[2]]' or why JS adds a ';' at the end of EVERY LINE. I mean Just look at this: function mynum() { return 1; } console.log(mynum()); // undefined I would submit to you that most OO people would have an easy time transition to ANY functional language that isn't designed to confuse because before we ever did OO, all of us did functions and can easily reason about them and how they relate to each other. The problem is the language, not the user!
- pjc50 9y agoWe should probably have two completely different versions of this discussion for typesafe and type-risky languages, since typechecking is effectively a form of testing at both unit and integration level.
- hinkley 9y agoI suspect I’ll be shifting from Node to Rust or one of its contemporaries at some point in the near future. I’ve given dynamic languages a very fair chance, kept an open mind and adopted its strategies instead of writing Pascal in any language, but it has failed to impress me. I want a statically typed language with reasonable affordances for FP, for the 20% of the code that is dead ugly when forced into object structure.
- lloyd-christmas 9y agoIs your decision mainly based on type-safety? We converted all of our nodejs to typescript primarily for easier refactoring, but it still hasn't fully satisfied our desire for change. We are thinking of switching to rust as well. We couldn't get past the Go generics argument, and would also prefer something staying towards the functional side. Any other languages you are considering?
- Illniyar 9y agoUnit tests and integration tests are tools, some tools are better at some tasks then others. The idea that a single tool is the only one you need is preposterous. If you are writing a library write unit test, if your app mostly binds two libraries together unit tests are meaningless, write integration tests.
- whack 9y agoYou've missed the point. Sure, code can always be written better to facilitate testing, but ultimately, each component of the code still has to correctly call/be-called by other components. No class exists in a vacuum. Suppose you have class-A which interacts with class-B. I've seen people put a ton of effort into unit-testing A and B in isolation, and writing very elaborate mocks/fakes/stubs for A and B. Only to end up with bugs anyway because they made a mistake in their mock/fake assumptions. Instead, an integration test that allows A and B to interact directly, and tests their resulting behavior, would avoid all this wasted effort and bugs that come from mocking. You suggest that instead of writing integration tests, this problem can be avoided by "writing better code". But how exactly would you rewrite the code to avoid the above problem? Declare that A and B should not interact at all, and move all their interactions into class-C? Now you've just given a new name to the same problem: "How do we adequately test class-C?" And once again, the correct answer is to ease up on the mocks and just write some integration tests.
- blauditore 9y agoI think many devs build applications only testing manually for a long time, and taking shortcuts (hacks) when something appears wrong. When they later want to write some unit tests, there are no proper units and that ball-of-mud-y code is hard to test. Of course, integration tests are still feasible because they're agnostic of the internal mess. I've run into this a couple times and noticed at some point that writing unit tests while developing (not necessarily TDD) helps a lot in clarifying boundaries early on, and generally improves code quality.
- BeetleB 9y ago>Unit tests run faster, are written faster, and not only can they be fixed faster, they can be deleted and rewritten if the requirements change. Honest question: Are most of your unit test failures due to bugs or due to refactoring (e.g. changing APIs)? Most people I know who do unit testing have mostly the latter (easily over 80% of the time). At that point one feels like they are merely babysitting unit tests. If unit tests have such high false positives, how useful are they? Note I'm not saying that it's not possible to write unit tests that are relatively immune from refactors. But it is more challenging and, in my experience, quite rare to find a project that writes them this way.
- hinkley 9y agoI’ll be honest, things that don’t cost me mentally or emotionally don’t even register. I probably delete more unit tests than I know and it simply doesn’t ‘count’ because they’re one action and one assertion and they’re wrong so poof. What I know is that when the dev team can’t adapt to shifting business requirements is a world of pain for everyone. I try to test a lot of business logic as low in the test tree as I can and when they change Always to Sometimes or Never to Twice, I roll with it. Because I know that Never and Always mean ‘ask me again the next time we court a big payday.’ What I remark on are the tests that get deleted when the business says they’re wrong. And those happen but the toll is easy with unit tests. You just ask and answer a different question and it’s fine.
- marcosdumay 9y ago> Why integration tests? Because they test that you are actually using some available network ports, have the correct database model in mind, didn't mistake the version of your libraries, got the deployment script right, and isn't just restarting everything in an infinite loop? Or maybe because E2E tests actually test stuff your company cares about, instead of some made-up rules that you've got from nowhere? Really, if you have unities, you should unit-test them. But your E2E tests should be the ones you really care about, and they should certainly not break randomly with unrelated development. If yours are lasting for 5 quarters, you may be doing something wrong.
- hinkley 9y agoThere’s a pyramid for a reason. It only takes a couple of tests to make sure that your plumbing connects all the way through. You inspect all the bits when they are going in but in the end you still check that things end up where they are supposed to. I’ve been doing automated testing for a while. It’s hard to learn, there aren’t many people to emulate. Well, there are people to emulate but the winning strategies are conterintuitive, so your gut fights you the entire time. It took me 8 years to feel confident in tests and my own test code routinely makes me sad because I find antipatterns and I should know better. Also other people copy all of my mistakes :/ I’ve seen a number independent groups two or more years into their testing adventure and the failure modes are not that different. Everyone pretty much makes the same mistakes I do, and it’s frustrating watching everyone go through the pain before they accept that something has to change and it’s probably them. The best strat I know of for testing is to use inductive reasoning and sampling to verify. If you don’t like the plumbing analogy then this is the Logic version of the same thing. If A -> B and B -> C then A -> C. Only a couple of your tests should verify A -> C and the bulk should check every kind of A [edit] and every kind of B. If you want to do things like this without making your code not ‘say’ anything (a huge pet peeve of mine, so I can empathize with your concerns) then there are a couple of things to do there. One is an old trick from Bertrand Meyer: split code that makes decisions from code that acts upon them. Beth is split leaves the code more legible, not less. Most of the boundary conditions are in the decisions. And this code is side effect free you can test the hell out of it with no mocks. Getting every permutation is straightforward and you can count your tests and your conditional branches to figure out if you are done. Once your code looks like this, adding and removing new rules to the system later is a snap. Even much later.