6 ms·
Prefer table driven tests (2019)
- atomicnumber3 3y agoI split tests into two categories. One is "I'm testing a bunch of different variations of the same thing." Table tests are great for this, they make the code pretty readable and, perhaps more importantly, the process of writing the inner part of the table test seems to nudge you to think about all the permutations and combinations of what you're testing can be. It leads to good tests and helps you reason about your inputs. The other kind of test is what I call a "storybook test." Table tests are less useful here, this is usually for testing CRUD in a coherent manner but can apply to any kind of object that has a lifecycle that you need to transition between various states. You may argue: aha! This is a state machine and you ought to simply independently test each state transition! Fair enough, I say, and yes in some cases I might actually do so if the API that's exposed lends itself to having its internal state set so explicitly. But more often than not I argue that the story itself is more valuable than exactly what permutations of the inputs and state get tested at each call. What the test represents is that some flow is important, gives an example of it, and helps show that this general use-case is what we want to keep working, not necessarily these specific state transitions. Mind you reality is messy so tests often blur and blend and so on. But when I sit down and write a new test, I'm usually imagining it as one of these two archetypes of tests.
- leetrout 3y agoAre you dogmatic about things such as only one assert per test case or similar?
- atomicnumber3 3y agoNot at all! Quite the opposite. I encourage people to write tests that make sense, are readable, and are a good use of their time. I encourage people to NOT write tests if they don't actually believe that it improves their belief the code actually works in prod, and also if they think it's not worth the LOC.
- lifthrasiir 3y ago> [T]he process of writing the inner part of the table test seems to nudge you to think about all the permutations and combinations of what you're testing can be. It leads to good tests and helps you reason about your inputs. I think this is not inherent. If you need to test all permutations and combinations, do the exhaustive property testing instead. Table tests (ideally) represent a pruned tree of possibilities that make intuitive sense to humans, but that pruning itself doesn't always neatly fit into tables. But otherwise I generally agree. When I write a specific set of tests I first start with representative positive cases, and I think you would call them as a storybook test (because it serves both as a test and an example). Then I map out edge and negative cases, but with a knowledge of some internal working in order to prune them. For example if some function `f(x, y)` requires both `x` and `y` to be a square number, I can reasonably expect that such check happens before anything else so we can only feed square numbers when we are confident enough that checks are correct. And then I optionally write more expensive tests to fill any remaining gaps---exhaustive testing, randomized testing, property testing and so on. Note that these tests are essentially sequential because each test relies on assumptions that are thought to be verified by earlier tests. Some of them can make use of tables, but the entire test should look like a gradient of increasing complexity and assurance in my opinion. Table tests are only a good fit for some portion of that gradient. And I don't like per-case subtests suggested in the OP---it just feels like a workaround over Go's inability to provide more contexts on panic.
- eru 3y agoBtw, those tables making intuitive sense to humans sounds like a strength, but it's also a big weakness. Humans aren't always good with thinking about corner cases. Property based testing is one way to get past this limitation. (As you also imply in the later part of your comment.)
- lifthrasiir 3y agoOne of difficulties with property testing is that humans are notably bad at specifying good enough properties. A canonical example is sorting: if your property is that every consecutive element should be ordered, an implementation that duplicates some element in place of others won't be caught. We can't always come up with a complete property, but intuitive cases can improve otherwise incomplete properties.
- hitchstory 3y ago>The other kind of test is what I call a "storybook test." Table tests are less useful here Storybook tests lend themselves well to forked tests. E.g. steps: ... - click: shopping basket variations: Empty basket: following steps: - click: empty basket - items in basket: 0 Purchase basket: following steps: - click: purchase ...
- eru 3y agoYou might like Hypothesis' approach to stateful testing. See https://hypothesis.readthedocs.io/en/latest/stateful.html https://hypothesis.readthedocs.io/en/latest/stateful.html I think what they call stateful testing is close to what you describe as a storybook test. Hypothesis is a property based testing library.
- lifthrasiir 3y ago> Please don’t email me to argue that map iteration order is random. It’s not. He definitely knows about this, but more clearly: there is no specified behavior about the map iteration order with a clarification that it can vary for each iteration of the same map, but the intent is that it is explicitly going to be unpredictable [1] and the main Go implementation always behaved like that since 1.0, so such argument is not exactly wrong. (I don't know whether this distinction is intentional. Most likely a simple oversight.) [1] https://go.dev/doc/go1#iteration https://go.dev/doc/go1#iteration
- eru 3y agoAs usually, Gophers might have some good ideas here and there, but they are stuck in their own world.. The obvious-in-hindsight next step up from table driven tests is property based testing. That's where you ask the computer to generate the tables for you, and also to automatically shrink any counterexamples it finds to be as simple as possible. See https://fsharpforfunandprofit.com/series/property-based-testing/ https://fsharpforfunandprofit.com/series/property-based-test... for an introduction. (One big benefit you get from property based testing is that the computer only needs to be taught once to always remember to also test edge cases like empty strings and zero length arrays, and NaN and infinity for your floats etc. Instead of a human having to remember for every test that zero is also a number. Of course, property-based-testing libraries also allow you to exclude those values, when they are not applicable. Eg not everything that consumes floats needs to handle NaNs. And explicitly filtering NaNs and infinities from your test case generation serves as good documentation for those kinds of assumptions.)
- boxed 3y agoAnd mutation testing... which in my opinion is just way easier to do and more mentally straight forward. Plus you get the satisfaction is actually knowing you're DONE, unlike PBT where you just give up after a certain amount of CPU time has passed.
- ReleaseCandidat 3y agoHow you write the tests that you're testing with mutatation does not matter. Or, to rephrase, you need both if you want to do mutatation testing (which is really slow).
- ColonelPhantom 3y agoThere's no silver bullet, not even mutation testing. For example, if the code for a certain case is straight up missing, there is nothing to mutate! I also consider mutation testing to be in a different domain from property based testing, as mutation testing is some kind of metatesting instead. PBT is a 'regular' testing technique. This means that they are in fact complimentary, for example by using PBT to check mutants. (Although mutation testing does seem to assume a sort-of 'fixed' test set, but you can also fix a test set with PBT by e.g. explicitly setting a seed and test count.)
- boxed 3y agoIn Python land this is called "parameterized tests": https://docs.pytest.org/en/7.1.x/example/parametrize.html https://docs.pytest.org/en/7.1.x/example/parametrize.html I think the author might want to look into mutation testing or property based testing to get to something closer to fully testing stuff.
- FrenchyJiby 3y agoYes, and going further, I think you'll enjoy the amazing lib Pytest-cases[1] which enables naming the parametrized tests, listing them not as decorators but as separate functions/classes. See the europython video intro: [2], or as slides[3] [1] https://smarie.github.io/python-pytest-cases/ https://smarie.github.io/python-pytest-cases/ [2]: https://www.youtube.com/watch?v=QTyfr2UNR98 https://www.youtube.com/watch?v=QTyfr2UNR98 [3]: https://ep2021.europython.eu/talks/649sqwq-powerful-tests-and-reproducible-benchmarks-with-pytest-cases/ https://ep2021.europython.eu/talks/649sqwq-powerful-tests-an...
- yellowapple 3y agoI'm fond of taking this a step further and actually offloading the test cases to a separate language-agnostic file, then have implementations' test harnesses read cases from that file. The Ruby gem for Base32H¹ does exactly this to test the encoder/decoder logic, pulling the test cases from CSV files in a separate repo² included as a Git submodule. One of these days I need to port the other reference implementations over to using the tests repo, but once that's done I'll be able to update the test cases in one place and they'll automatically work everywhere. ---- ¹ https://github.com/Base32H/base32h.rb/tree/master/spec https://github.com/Base32H/base32h.rb/tree/master/spec ² https://github.com/Base32H/base32h-tests https://github.com/Base32H/base32h-tests
- eru 3y agoWhat do you gain from having a separate language agnostic file? If you are going to have a table, it seems to make sense to have the table next to the code that's using it. (Though I prefer property based testing.)
- yellowapple 3y ago> What do you gain from having a separate language agnostic file? Right now, nothing. In the future, when I overcome my laziness, it's a single place to define tests that multiple projects in multiple languages (in this case, encoding/decoding libraries) need to pass in an identical manner. If I ever identify more edge cases that I need to test, I can add them in one place and all existing implementations would automatically test them, and for future implementations I only need to implement enough to read and loop through the test files and then I'm done. Another advantage comes about in the corporate world (where most of my programming energy has less-than-fortunately gone): having test cases defined in a format like CSV that Excel can edit makes it easier for non-programmers (i.e. the vast majority of stakeholders for the average corporate software project) to read and write the test cases.
- deleted 3y ago[deleted]
- DarkNova6 3y agoWow… this can’t possibly be how you write tests in Golang?! Code: https://hastebin.com/share/puciyelayi.go https://hastebin.com/share/puciyelayi.go This is just insane, the ceremony is twice the length of the actual testing code. I seriously hope this is not representative of the language as a whole. In Java I get the outcome with the Annotation @ParameterizedTest.
- zb 3y ago> this can’t possibly be how you write tests in Golang?! Only for very simple functions like in the example. Most of the time it’s much worse.
- kitd 3y agoThe "ceremony" is just the for loop and the t.Run( ... ) call. Everything else you'd need to do in Java too.
- rswskg 3y agoI was getting the same feeling.
- mrkeen 3y agoCan you write up the Java version too? I don't think it would be significantly more terse. Maybe you'd lose the: for name, tc := range tests { t.Run(name, func(t *testing.T) { But gain: @ParameterizedTest
- 3y ago
- stpedgwdgfhgdd 3y agoTable driven tests are fine for more than, let’s say 6 test entries, but otherwise a set of assert or require is much more pleasant to the eye. AND if you want to debug, just click on the stacktrace in your IDE and set the break point for that failing test. Way faster. Again, table driven tests definitely have their place, but in the spirit of XP, it is not the most simple thing out there. Do not use by default.
- athorax 3y agoYou can target specific table driven tests by name in order to just run/debug a single case
- vvern 3y agoTable driven tests are a lot better than a bunch of imperative tests but they rapidly become unwieldy to debug, maintain, and evolve. Their readability often isn’t great. If you’re using go, check out https://github.com/cockroachdb/datadriven https://github.com/cockroachdb/datadriven. It takes a little bit of effort to craft a testing dsl, but it is so worth it. Also, snapshot style testing where the test writes out its expectations and you just inspect it and save it (part of datadriven) is wonderful. I’ve been using insta in rust lately and it’s some of what I want but not quite datadriven.
- malablaster 3y agoI also can’t stand when I want to debug a single table test with VSCode debugger+dlv and I have to comment out hundreds of lines of table tests.
- arwineap 3y agoTest how it makes sense for your use case. Table driven tests are fine, and I use them for cases that call for it.
- kazinator 3y agoThe goal of this incredibly long-winded detour seems to be to avoid having something reasonably nice like: https://www.kylheku.com/cgit/txr/tree/tests/015/split.tl https://www.kylheku.com/cgit/txr/tree/tests/015/split.tl
- adrianmonk 3y agoI'm not convinced this is better than just using functions. Change TestSplit() into DoTestSplit(), give it function parameters (input, sep, and want), and let it do all the work of calling Split(), comparing actual against expected, and failing with a good error message. Then call it from four one-liner functions TestSplitSimple(), TestSplitWrongSep(), TestSplitNoSep(), and TestSplitTrailingSep(). The test framework can then have the right number of test cases and report failures the right way because there's still a separate function for each test case. (Or I assume so. I don't know Go.) And to me, this is less cognitive load than, "Oh, here's a map literal, and the name passes through from here to t.Run()." When reading this, I'd rather focus on what I'm testing than how the table-based testing is doing it. I think tables and sub tests would be useful in certain specific situations, though. I'm sure they're more concise if you have 25 cases instead of 4. In some cases, you might have two or more tables and want to test all possible combinations.