by thomascgalvin · 6y ago · 0 comments
This is one of those things that sounds good when you're in college, and sounds, well, horrifying is too strong a word, but it will definitely set off the warning bells for anyone that's been programming for a decade or more.
My team has a simple standard: every single user-facing requirement is verified by automated testing. We don't have 100% coverage, but it's damn close, somewhere like 98%. The remaining untested code is generally weird branch paths that are hard to trigger, and "shouldn't" be seen in production.
But this goes beyond code coverage or TDD: firing up the debugger and executing a unit test is the simplest way to add a feature, period. I cannot fathom building and starting our application so that I can hand test every time I change a line of code.
Unit and integration tests aren't punishment inflicted on inferior developers: they'd an extremely useful tool that makes your life easier and your team more productive.
Speak for yourself :) I'm a huge TDD advocate, and I'm personally responsible for making testing a requirement of any dev work in my company. I am well over a decade in experience.
Gary's quote sounds pretty close to my criteria for what to test (my criteria would replace "a lot of details that can't be statically checked" with "meaningful details that can't be statically checked").
The type system cannot replace all testing, but there are certainly places where it can make testing superfluous. Increasingly I strive to make more and more of a codebase like that. It improves confidence in the system, with a significantly faster red-green cycle, and isolates complexity to layers of an application where complexity is expected.
> But this goes beyond code coverage or TDD: firing up the debugger and executing a unit test is the simplest way to add a feature, period. I cannot fathom building and starting our application so that I can hand test every time I change a line of code.
In general, I agree with this, and in general this is my approach to programming. However, and this is a sincere question: do you work on web frontends? In my experience, some aspects of frontend work is absolutely easier to evaluate by simply running it. You may want to have automated tests for certain interactions, but even then as a regression test, as writing the test first is often harder than getting it working first and making sure the test exercises it after.
I agree. We configure analysis to ignore boilerplate code, for example, so that doesn't count toward out coverage threshold.
And in this particular example, yeah, there is an entire class of tests that no longer need to be written; the "did he really pass me an integer, or is it JSON" style assertions. Typescript (and strong typing in general) is super helpful for eliminating that category of test.
> However, and this is a sincere question: do you work on web frontends?
When I'm forced to. I'd say my work in 80% backend, 20% frontend, though that ratio changes based on what stories we pick up for the week.
But we use TDD for our frontend, too. I have selenium tests that bring up the backend, launch the web UI, and run through the required functionality.
It's a very different mentality, and we don't check things like CSS layouts at this level, but the general "the user clicks this button and gets this result" are all verified automatically.
I hear you. And I think this may account for some of your frontend testing solutions. (Which I in now way mean to disparage.)
Given a set of technologies that allow it, another way is possible, significantly easier, with a faster red-green cycle and probably a higher degree of confidence. It looks a lot like what Gary described in TFA. Given:
- A good type system
- A component system with single-direction data flow
- A state abstraction that is testable outside of the DOM
(Edit: not sure why HN won't let me make a list without empty lines but there you go)
In quite a lot of cases the tests can be isolated to your state logic, and the mere presence of a component and a passing compilation is enough to ensure your frontend works. You can even, with some effort, ensure the presence with the type system.
It doesn't necessarily eliminate all end to end testing scenarios, but for a lot of sites/apps it may.
because hn formatting doesn't actually have a "list" concept https://news.ycombinator.com/formatdoc
Generally I find tests that test the controllers, where multiple units of work are attached together, to be much more useful. But TDD does not naturally lead to these kinds of tests.
Generally, by describing tests in plain english that express "user" intent (where "user" may be the dev at the call site, or may be an end user) rather than expressing things like return values or state changes.
> In order to add or change a feature, you now have to write the code twice: Once to implement the change, and once to re-implement the change to assert that it does what it's supposed to.
From this description, it doesn't sound like you're doing TDD.
1. Write a failing test (where "test" describes user intent). 2. Make that test pass with an implementation. 3. Make that implementation meet your expectations for code quality, appropriate separation of concerns, appropriate abstraction, DRY etc.
(This is commonly referred to as red-green-refactor.)
> And no safety has been added, because the logic itself can still be flawed. You've just written it twice instead of once.
While you can always get the logic wrong, it's significantly less likely if what you're testing is intent. I really don't understand what you mean by "written it twice".
> Generally I find tests that test the controllers, where multiple units of work are attached together, to be much more useful.
I'm... honestly surprised by that. Those tests tend to be the most brittle, the least likely to cover all scenarios you'd like to test, the most error prone, and the hardest to understand and maintain.
While true, it's far more likely that they will help you during a refactor. If you use TDD and have a test for every function, you will more often than not throw entire functions and their tests away. A million tests that test immutable functions are all useless. But tests that fall in between TDD style test-per-function and integration tests, tend to be re-used post refactor, and give certainty that the refactor worked as expected.
I think you have that backwards.
In TDD, the test is basically an assertive statement: when this test passes, the functionality is working as intended. You then write the implementation code, and when the tests pass, you're done.
This gives you two things: one, a sense of certainty that your code is meeting the requirements, and two, it bounds your work, preventing you from writing code that you don't need to make the test pass.
Now let's say we're changing a feature. Maybe if a user tried to add an out-of-stock item to their cart, the UI currently displays an error message, but now we want to add a note indicating when the item is expected back in stock.
We'd just go into the test for that error message, and add statements that look for this new `div`. We would probably have to add a few cases (for example, when we have an estimated data, when we don't have an estimate, and when we've been told the product won't be restocked), but we aren't fundamentally altering the test code.
These tests will initially fail, because there's no `div` with an `id` of `restock-message` or whatever. But one by one we can knock them out, adding messages for known or estimated restock dates, unknown restock dates, and permanently out-of-stock items.
> And no safety has been added, because the logic itself can still be flawed.
That's true, but that would also be true if you were hand-testing. You can't verify functionality you don't understand, but you can't write functionality you don't understand, either.
TDD, and testing in general, isn't a magic bullet that solves all of your problems; at some point, you still have to be smart enough to write the code. But testing is still a necessary tool in the developer's toolbox, because without it, you simply cannot know that your code is doing what you think it's doing. And since you're going to be testing anyway, why not have the machine do as much of the heavy lifting for you as possible?
This is where TDD really falls apart for me. It's pretty rare, at least in the code I work on, that you add a single little bit of functionality that fits cleanly into an existing TDD function. It's much more common that entire structures changes, and the TDD tests are no longer relevant and have to be completely rewritten from scratch. So again, you're effectively just implementing the logic twice. Where you actually need it (during a refactor), it provides no safety because it just gets completely rewritten every time.
I can't agree with this more and also find the reverse is true: not having tests will punish you repeatedly. If we measure inferiority by unproductivity, adding tests also enables you to become the opposite of inferior (ferior?)
"superior"
To someone that has programmed for a good 2 decades and more, the above sounds like what a college student or junior dev that just found out about TDD would say.
Unit test and integration tests are (bad) substitutes for good and modular design, which should piggyback on a strong type system. I've seen it so often that whenever I read comments like the above I feel the need to create an HN account just to reply to them.
Junior devs in charge of major design decisions create damage that goes way beyond their limited reach. Test code is untested code. Test code is brittle code - especially integration tests are. You need tests because you're using a dynamically typed language? Well, stop using that language for anything that is even remotely complex. Your future senior dev self will thank you.
This sounds completely hand wavy. If the design is in fact modular and built of autonomous components then it should be relatively easy to test and should be tested. Types are no substitute for testing and are completely orthogonal to testing.
> Test code is brittle code
If this is the case then the code being tested is more than likely brittle as well. Test code reflects the system under test more than anything else.
> You need tests because you're using a dynamically typed language
No you simply need tests in any language.
I don't agree with the person you're replying to that types make tests redundant, but to claim that types can't substitute a large amount of testing can only come from inexperience.
Whatever property you can model successfully through a closed type, is a property you never have to test ever again anywhere it's being used. If you have 500 functions that take a NonEmptyString, those are 499 fewer property checks in tests (because you should have one test for the type constructor).
That is a very bold assertion I have seen no evidence for. I write very few tests in Ruby or Javascript aimed at validating types.
I don't really understand the connection between a dynamically typed language and the need for (or lack of) testing. Can you explain what you mean? I've never once felt like the type of language I used defined how important tests were.
When I write a unit tests, I'm not looking for syntax errors or a scenario where I'm passing the wrong type in, I'm verifying that the business rules of my domain are being properly enforced.
If your unit test is brittle, I'd say that's a pretty awful unit test. You should be isolating the component you're testing and eliminating all external dependencies like in the example below.
class ItemRecommenderGuardTest extends TestCase
{
public function setUp()
{
$dependency = Phake::mock(Dependency::class);
$this->recommenderGuard = new ItemRecommenderGuard(
$dependency
);
}
public function testGuardsInvalidItem()
{
// business rules deem this item un-recommendable. This unit
// test verifies that the guard class properly enforces these rules
$item = /* ... */;
$this->assertFalse($this->recommenderGuard->isRecommendable($item);
}
}
This test isn't brittle, and it's asserting that an item which does not meet recommendable standards is never recommendable. If someone comes along and modifies the guard class incorrectly, these unit tests are here to maintain the integrity of the systemUnit and integration tests are not "substitutes" for good and modular design. Good and modular design work hand in hand with tests to produce reliable, well understood, and maintainable code. The most testable code is usually often the most well separated code.
A strong type system provides the third leg of the tripod. It's not replaced by or a replacement for either of the other two.
Stop thinking that you're too good for test code. Your future senior dev self will thank you.
That's a complete non-sequitur. You can have spaghetti code that produces a correct result, and you can have a beautiful architecture that produces an incorrect result.
Testing is the only way to verify whether or not your code is producing the correct result. You can test by hand or automatically, but the ultimate determination on the correctness of the code relies on a test.
It has nothing to do with design.
And people forget the main thing about TDD: The main goal is to validate your design
You don't get that with type systems.
Depending on the code it is possible to construct the types in such a way that an incorrect implementation is very hard. This requires a modern type system and the knowledge to use it effectively. Type systems like in Java and Go are not up the task for the most part.
For example, some things are a lot easier to test than others. Some things require a lot of setup that is tedious and error prone. In such cases, it's preferable to test at a lower level but it's not always possible to do that and still cover all relevant cases. Those are the cases where unit tests tend to be the most expensive.
100% test coverage may be desirable as a goal, but not at any cost, and tests absolutely do incur costs. So there is a trade-off, and it's worthy of consideration.