393 comments

[ 3.1 ms ] story [ 279 ms ] thread
You may find this article interesting: https://medium.com/chrismarshallny/testing-harness-vs-unit-4...

I think unit testing definitely has its place. I use it a lot; but I have learned to moderate my reliance on unit testing.

I tend to prefer test harnesses and manual (or automation-assisted) testing. I've sometimes written my own unit-testing frameworks, because the "canned" variants didn't give me what I needed.

The term "unit testing" is quite old. It seems to mean something different, these days, from what it used to mean.

As far as I'm concerned "not testing my software" is out of the question.

For most of my projects, the testing code is vastly greater than the actual product code.

Unit tests are very important and very cheap. They safe a huge amount of grief later on.

As for everything, the pros and cons should be weighted to reach a practical and effective approach. For example there is rarely a need to test every single function.

Overall, I don't find this piece very insightful.

> For example there is rarely a need to test every single function.

And that's where the bugs end of being.

People suck at writing code so it needs to be reviewed by peers and thoroughly tested. If you said that in an interview for code you'd written then I'd point to the door.

It's always a question of balance and return of investment. It's good to aim for 100% coverage, but it's a diminishing return exercise and it may not be particularly valuable to reach it, so in practice it usually remains an aim.

> If you said that in an interview for code you'd written then I'd point to the door.

That's an extremely arrogant thing to say. Any experienced dev will understand my point, so...

Most programmers are arrogant and that's why they write terrible code full of bugs. I posted elsewhere that if your code isn't tested then it's broken. It was sitting at negative four when I last looked. That comment should be in the hundreds. If folk don't understand that then they need to look into their software development practices.
Typical 100% coverage metric vanity with usually no real world benefits.

> If you said that in an interview for code you'd written then I'd point to the door.

And they would be better off not having to work at a place with an intolerable environment of the kind.

You aim for maximizing code paths in the minimum test cases. Test cases written correctly can be quickly reused with different input values. Design to test. Prove your code through automated unit testing. Skipping proper test development leads to terrible tech debt when you try to maintain the code. Error paths are generally the place that doesn't get most coverage and those are where you crash a lot of programs. This stuff is elementary.
God I hate this stupid industry so much
So you would write test cases for all the methods and constructors for a class like this:

  class Foo{
    public Foo(initialValue) {
        this.value = initialValue
    }
  
    public setValue(value) {
        this.value = value
    }
  
    public getValue() {
        return this.value;
    }
  }
What's the point, what are you testing? That the language's most basic operations still work?
You'd test those cases. This way, if you'll change your code to be

``` public setValue(value) { this.value = value + 5 } ```

then your tests will start to fail.

Treat tests as a contract.

Can't tell if serious...
They are. If you don't get it then you're doing it wrong.
I'm serious. Of course you don't test that language operations work, but you're testing that given method does what it's supposed to do. In this case your method sets value for property on model. It doesn't matter you're doing it via assignment - you could be doing it by any other ways. You want to test that for given model after calling that method your models property will change to given value. This way, if you'll change the implementation of setValue your test will still succeed. If it'll start doing something else, they will fail. And of course, this method can be used in your feature tests, so those will start failing too (but that's beside the point, I guess)

Of course it's also a balancing act - should you immediately write test for this? I try to.

They are cheap per unit, but if you test a lot of units, it adds up.

There is a set of bugs that only higher-level testing will catch. There is another set of bugs that both higher and unit-level testing will catch. Then there is the set that only unit-level testing will catch.

How important is that last set? If a unit test fails and there is no user interaction to trigger that failure, is it really a bug?

Unit tests can be valuable if they help you during development of a unit, but most units are not that complex and should not require unit tests.

Cost includes the impact on further tests and maintenance.

The cost of testing and debugging increases as you go down the development/release cycle.

If you have unit tests then that helps integration tests (less issues, easier to investigate), system tests, etc. all the way down to dealing with bug reports from the field.

> but most units are not that complex and should not require unit tests.

That is a very bold claim...

> If you have unit tests then that helps integration tests (less issues, easier to investigate), system tests, etc. all the way down to dealing with bug reports from the field.

Not in my experience. I don't see how a unit tests helps me with bugs that show up in the field. If it shows up in the field, something should've caught it, which means testing failed.

> That is a very bold claim...

I'm a bold guy.

I initially reacted very negatively to this article but decided to entertain the idea anyway and I have to say I'm convinced of the idea that they are overrated.

Now I'm not saying that they are unnecessary and i definitely believe they are needed but i do think they are overrated.

I've worked on many buggy systems that had very good unit test coverage. It was only with sufficient integration testing that were able to prevent constant regressions.

Unit tests are not integration tests.

Of course if your integration tests are lacking you'll have problems but this does not tell you anything about the value of unit tests, just that integration tests are obviously valuable.

Unit tests have their place but in my experience there are also a lot of places in most codebases where they don't deliver enough value compared to the effort put into both writing and maintaining them (they can be a huge PITA while refactoring). I agree that in many cases integration tests often are so much more useful in catching regressions.
> they can be a huge PITA while refactoring

I see that as an useful feature: This shows you the cost of refactoring and the fact that this cost includes re-testing everything.

I see unit tests as executable documentation. So it's nice when code you're getting familiar with has good tests. That said, I don't write them myself, except when the code is complicated and difficult to predict, but then I'm more likely to refactor it.
The author agrees with you, in that he makes the same recommendation around testing the functionality rather than the functions.
Knowing that some component provable works correctly is underrated though. I would favor

- 33% unit tests (of well-defined units, such as functions that compute some subtle math logic, or read/write marshalling)

- 33% integration tests (requiring multiple components to work correctly to achieve the result)

- 33% business tests (automatically steering the entire application like a user would and testing the result like a user would see it)

And the remaining 50%: making it easy for people to give you useful feedback, such as error messages giving a web link to a user-friendly bug tracker. Ideally the link already fills in the stacktrace and system info.
I always argue for this and get told, “that’s not for the user. It’s adds screen bloat to the UI.” I never understand why people say that. How about we make it easier for us to help people. I mean at the core that is kind of our job.
This! Not just for the systems development side of things, but just as much for normal usage. I tend to do work for fairly small organizations (<500 ppl), but with layer upon layer of bureaucracy and management, not to mention cultural and geographic differences.

The main goal of the systems I work on is to provide technical documentation of complex industrial processes. If things break, it can be pricey and/or dangerous. Having good information is a must.

However, if a user sees that something is off or just plain missing in the sometimes 30+ year old documentation, the easiest way to deal with it is to make a note of it and adapt to it for his or her work. Reporting the problem back in order to get it fixed is....difficult. There probably is a process for it, you probably don't have an account where you can log the time spent on it.

Having a quick and low-threshold way to report problems would be of enormous value in the long run.

I read it and I already knew that I had this discussion a bazilion times, just like every comment in HN probably won't be anything new to me.

Some topics are just made to be discussed forever

If it's not tested then it's broken.
I can imagine you can argue in favour of any statement, given your custom, ad-hoc anecdotical use case. However, in general terms, unit testing (together with a very clear domain design) are the most solid pilars of your software.
What’s with the recent HN push against unit tests? Yes you need other tests too, but they serve a purpose. You can’t build on bad foundations! And the search space of integration tests is larger so it’s much harder to have good coverage of non-happy paths
you can have good experiences with unit tests or bad ones depending on the health of your codebase. Hard to test code is a smell that many people interpret as being a problem with the concept of unit testing.

Most of my experience is with React, and the majority of react devs I've seen don't unit test their code, because they don't write enough pure testable functions. As a result the community has leaned heavily on React Testing Library which is AMAZING for integration testing. Instead of checking that your function returns the right value, people will mount the component and then check to see that the right value is displayed in the rendered DOM. This obviously works, but writing the logic as a pure function and unit testing that function with a lot of different inputs gives you much more confidence.

I think it's a critical mass of people experiencing the "unit tests pass but the code is broken" problem. When unit tests are used to test glue code you end up testing your mocks and nothing else. Mocks are often done using a framework which encourages one off implementations per unit test. This introduces a maintenance burden where all the mocks have to be kept in sync.

Unit tests are very useful but we somehow landed ourselves in a place where we have lots of line coverage in our unit tests but little confidence that the code actually works.

There are at least 3 different applications at work where they unit tests are green while the code is broken or red when it's not. The cause is almost always the mocks. They either presume too much, making then fragile or they are flat out incorrect. Despite having a lot of test coverage there is little confidence for the developer that their change is correct.

In a sense the writers of the tests were "doing it wrong". The burst of articles on unit tests and their failure modes are a reaction to the prevalence of this in our industry.

Similarly, the unit tests never catch bugs and you're always changing them because of refactors or changing requirements. At some point it's like 'hey this set of tests have been rewritten 3 times and they never caught anything, so ... like does that mean that we just wasted time for the first two times?'

I've seen unit tests as documentation cause problems a few times. Like, maybe if you've got some sort of DSL where it's actually obvious what behavior is expected. However, more often it's 10-50 lines of setup / mock code and then some number of asserts and you're left trying to decide what the point is (ops, it turns out something got misinterpreted and the test is actually nonsense).

Finally, it seems like using the type system to design code where illegal states are not representable is starting to make some headway. Additionally, we're seeing increasingly powerful type systems make it into industry acceptable languages.

Even with typed driven development you still want unit tests in the form of property based tests. Also a nice way to resolve the 10-50 lines issue is to follow the Arrange, Act, Assert pattern where you could look at the second block to see the actions. Move as much of the Arrange section into a setup and it should be a bit clearer :)
I really like property based tests. They feel like they're everything that unit tests without them were supposed to be.

* More closely encodes the behavior you want the code to have

* More likely to find weird edge cases where some input does something unexpected

* Less work to get greater coverage

> people experiencing the "unit tests pass but the code is broken"

Arguing against unit testing is like arguing against type-safety (and, usually, anti-unit-testing people are anti-type-safety people, too). The presumption always seems to be that if it doesn't solve every problem, it's unnecessarily slowing things down.

In my experience it's the pro-unit-testing people who are more likely to be anti-type safety people. The argument against type safety typically goes something like this:

I already have to write unit tests so why would I bother with types they don't add any real value.

Both camps are wrong. Unit tests are an unambiguous good. Types are also an unambiguous good. Both have some rather common failure modes though and guarding against those failure modes is useful.

Unit tests of purely functional code where you only need to provide an input and validate an output provide tremendous value. The unit test can treat the code as a black box and as a result the unit test is robust and resilient to changes in the black box while verifying that the box still produces the correct answer. Unit tests of code with hidden dependencies that need to be mocked require a lot more care to construct properly. Mock scripting frameworks encourage a number of bad habits. Things like "How many times did this method get called". Or "Always provide the same answer when this method get's called." The result is a hundred reimplementations of the same interface that are at best correct for the current version of the code they are testing and at worst completely incorrect reimplementations of whatever they are mocking. They all need to be kept in sync and maintained over time.

A shared in memory Fake will in general provide more value and be less fragile over time while also ensuring that your tests are actually testing the code and not the particular script you defined for the mock.

> (and, usually, anti-unit-testing people are anti-type-safety people, too)

This is the opposite of my experience. Most of the anti-unit testing people I've talked to are very much pro-type people. I wonder if anyone has done any studies that shows what the actual numbers look like.

> Arguing against unit testing is like arguing against type-safety

I disagree with this. Types (at least when they've been built on top of an actual logic) have the benefit of real costs and benefits. You can show what programs you are unable to write and you can show (mathematically) that certain failures won't happen.

Unit tests on the other hand are much more hand wavy. You can show that some refactors seem easier, but you can't prove it without a lot of data that has to be collected on a project by project basis. I'm not saying that I don't want unit tests if I'm doing a non-trivial refactor, but I am saying that that desire is more of an intuition thing. It's not like I can make any proofs around it like I can do with a type system.

People don't know how to test well. It's that simple.
More like all languages are not equally easy to test. Just like all languages are not equally easy to write. It's incredibly easy to write mocks/spies in javascript without a single third party library. It's tedious to do that in Java.

There is also a corporate culture of tests that mandates bloated test frameworks, which leads to developers spending more time on writing tests than writing functional code.

Is writing tests more than functional code actually a bad thing? Isn’t that just a part of engineering?
That depends on if you are shipping tests to customers. Most companies are shipping code, not tests, so time spent on test is time not spent on code. You only want tests that make code easier to write.
You’re not just shipping code, you’re aiming to ship a correct program right? And tests are a part of that and will be on the list of risks the customer may be concerned about. It’s not just about making code easier, it’s about showing the code works as expected.
It takes skill to know which parts to test with unit tests.

If you start striving for over 100% unit test coverage, then you'll be testing if the IDE pre-generated setters and getters actually set and get the value. This adds zero value to the codebase and you'll be testing things that, if they fail, will break half the world anyway.

Unit Tests are for algorithms, stuff that does something complex and not immediately obvious. Preferably deterministic, every time X goes in, X+Y comes out type of stuff.

Most tests should be either integration tests, testing the interfaces between different parts of the software or automated tests pretending to be the user, made with Robot Framework or something similar.

I disagree with the notion that making your code testable in isolation serves no other purpose than to write unit tests. It very specifically forces you to think about how and why each piece of code is coupled with other code, and generally requires you to make this coupling as loose as possible, to make testing in isolation possible. Loosely coupled code is also easier to reason about and easier to refactor. So testing doesn't just provide you with the value of tests, it also nudges you toward a saner architecture.
I strongly disagree for the reasons listed in the article; it induces the construction and testing of abstractions which exist solely to enable testing, and do not enable simpler reasoning.

Refactoring is even worse. Refactoring after you've split something up into multiple parts and tested their interfaces in isolation is far more work. Any refactoring worth a damn changes the boundaries of abstractions. I frequently find myself throwing away all the unit tests after a significant refactoring; only integration tests outside the blast radius of the refactoring survive.

Maybe your unit's are too big. Unit tests are tricky because it's about coming to a personal and team agreement on what a 'unit' of functionality is.

I find the same issue in throwing away tests when I'm writing small scale integration tests with junit. Usually I'm mocking out the DB and a few web service calls. So those tests become more volatile because their surface is exposed more. But smaller level, function and class level tests can have a really good ROI and they do push you design for testing which makes everything a bit better imo.

It's normally the opposite. Unit tests are too small.

If you unit test all of the objects(Because their all public) then refactor the organisation of those objects then all your tests break. Since you've changed the way objects talk to each other, all your mock assumptions go out the window.

If you define a small public api of just a couple of entry points, which you unit test, you can change the organisation below the public api quite easily without breaking tests.

Where to define those public apis is a matter of skill working out what objects work well together as a cohesive unit.

The notion of a public API is really more fluid in the context of internal codebases as well. It's important to maintain your contract for forwards/backwards compatibility when publishing a library for a world. When you can reliably rewrite every single caller of a piece of code, you don't have that problem.
I usually test whatever subset of code could be tested with less than about a dozen of test cases. If it's larger then test logical parts of it with mocks in the leaves. For small projects it could be usually a single controller with only some mocks on the edge of the system (database, external APIs etc.). Refactoring the code where there is one test suite per class could be a nightmare.
if it is worth rewriting the code it's worth rewriting the tests.
Seems to defeat the point of the tests. At least partially.
Not if you rewrite/change the tests first, since you know the code currently works and you are safe to refactor the tests. Equally you are safe to change the tests to define the new behaviour, and then follow on with changing the code to make it green.
The point was to change the code structure without changing the tests (possibly to enable a new feature or other change). The challenge being when the tests are at the wrong "level", probably by team policy IME. If you change the tests, how can you be sure the behavior really matches what it was before?
Agreed. I see tests as the double entry accounting of programming, they let you make changes with a lot more confidence that you're only changing what you want and not some unexpected thing.

They're not for catching unknown bugs, they're for safer updates.

Unit tests test that the units do what they are supposed to do. Functional tests test that parts of the system do what it's supposed to do.

If you change the implementation for a unit, a small piece of code, then the unit test doesn't change; it continues to test that the unit does what it's supposed to do, regardless of the implementation.

If you change what the units are, like in a major refactor, then it makes sense that you would need whole new unit tests. If you have a unit test that makes sure your sort function works and you change the implementation of your sort, your unit test will help. If you change your system so that you no longer need a sort, then that unit test is no longer useful.

I don't see why the fact that a unit test is limited in scope as to what it tests makes it useless.

I'm definitely a fan of higher level tests that frequently survive refactorings.

I'm not arguing unit tests are useless.

If a particular test never finds a bug in its lifetime (and isn't used as documentation either), you might as well as not have written it, and the time would be better spent on something else instead--like a new feature or a different test.

Of course, you don't know ahead of time exactly which tests will catch bugs. But given finite time, if one category of test has a higher chance of catching bugs per time spent writing it, you should spend more time writing that kind of test.

Getting back to unit tests: if they frequently need to be rewritten as part of refactoring before they ever catch a bug, the expected value of that kind of test becomes a fraction of what it would be otherwise. It tips the scales in favor of a higher-level test that would catch the same bugs without needing rewrites.

> If a particular test never finds a bug in its lifetime (and isn't used as documentation either), you might as well as not have written it

That's like saying you shouldn't have installed fire alarms because you didn't wind up having a fire. Also, tests can both 1) help you write the code initially and 2) give a sense of security that the code is not failing in certain ways.

> It tips the scales in favor of a higher-level test that would catch the same bugs without needing rewrites.

Writing higher level tests that catch the same bugs as smaller, more focused tests is harder, likely super-linearly harder. In my experience, you get far more value for your time by combining unit, functional, system, and integration tests; rather than sticking to one type because you think it's best.

My comment went on to say that you don't know ahead of time exactly which tests will prove useful. So you can't just skip writing them altogether. They key point is that if you have evidence ahead of time that a whole class of tests will be less useful than another class (because they will need several rewrites to catch a similar set of bugs) that fact should inform where you spend your time.

To go with the fire alarm analogy and exaggerate a little, it would work like this: you could attempt to install and maintain small disposable fire alarms in the refrigerator as well as every closet, drawer, and pillowcase. I'm not sure if these actually exist, but let's say they do. You then have to keep buying new ones since the internal batteries frequently run out. Or, you could deploy that type mainly in higher-value areas where they're particularly useful (near the stove), and otherwise put more time and money in complete room coverage from a few larger fire alarms that feature longer-lasting batteries. Given that you have an alarm for the bedroom as a whole, you absolutely shouldn't waste effort maintaining fire alarms in each pillowcase, and the reason is precisely that they won't ever be useful.

There are side benefits you mentioned to writing unit tests, of course, like helping you write the API initially. There are other ways to get a similar effect, though, and if those provide less benefit during refactoring but you still have to pay the cost of rewriting the tests, that also lowers their expected value.

To avoid misunderstanding, I also advocate a mixture of different types of tests. My comment is that based on the observation that unit tests depending on change-prone internal APIs tend to need more frequent rewrites, that fact should lower their expected value, and therefore affect how the mixture is allocated.

I get what you're saying and it makes sense to me.

> unit tests depending on change-prone internal APIs

This in particular is worth highlighting. I tend to now write unit tests for things that are getting data from one place and passing it another, unless the code is complex enough that I'm worried it might not work or will be hard to maintain. And generally, I try to break out the testable part to a separate function (so it's get data + manipulate (testable) + pass data).

Sorry, that should be "tend to not write".
> I frequently find myself throwing away all the unit tests after a significant refactoring

Good, this time you can get it right.

> the construction and testing of abstractions which exist solely to enable testing

One of his examples from the article is injecting, IOC-style, the HttpClient instance into his LocationProvider class. He insists that this is a waste of time, and that the automated tests (if you have any at all), should be calling out to the remote service anyway. I can't disagree more! Hopefully you're configuring the automated tests to interact with a test/dev instance of the service and not the production instance (!). But what invariably happens is that the tests fail because the dev instance happened to be down when they ran. And they take a long time to run anyway, so everybody stops running them since they don't tell you anything useful anyway. This is even worse when the remote service is not a web service but a database: now you have to insert some rows before you run the test and then remember to delete them... and hopefully nobody else is running the same test at the same time! To be useful in any way, automated tests must be decoupled from external services, which means mocking, which means some level of IOC.

On the other hand, he also introduces the example of SolarCalculator mocking LocationProvider. I agree that that level of isolation is overkill and will unapologetically write my own SolarCalculator unit test to invoke a "real" LocationProvider with a mocked-out HttpClient, and I'll still call it a unit test. (On the other hand, the refactored designed with the ILocationProvider really is better anyway).

So I think the reason people argue about this is because they can't really agree on what constitutes a unit test. I'd rather step back from what is and isn't a unit test and focus on what I want out of a unit test: I want it to be fast, and I want it to be specific. If it fails, it failed because there's a problem with the code, and it should be very clear exactly what failed where. A bit of indirection to permit this is always worthwhile.

You often end up reimplementing the "comsumer" module for your code in order to test. This is problematic because a) extra work and b) that fixture layer probably doesn't behave exactly like the real caller code and c) now you have to keep those two implementations in sync.
There shouldn't be anything particularly complex in test code, limiting the extent of any "reimplementation". Moreover, if the test client is different from real clients and not "in sync" it's a good thing: unit tests that do something differently within the limits of documented acceptable behaviour expose assumptions and bugs. For example, suppose outputs should be sorted in a certain way, but they are sorted if a client presents sorted inputs and not because they are actually checked and sorted: a test with random inputs can expose the hole.
> Loosely coupled code is also easier to reason about and easier to refactor.

Can you expand more on this? I think this is where the author would disagree.

E.g., how is the code easier to reason about or refactor having introduced a location service interface that has only one one implementation?

Suppose you have a unit that makes a couple of api calls to set itself up, then performs a computation, then does some sort of storage. Thinking about how you would test this might lead you to an inversion of control approach, and you might isolate side effects. The storage provider might get passed in, both to make it easy to mock, and to reduce coupling and surprise.
I meant expand on how those things make code easier to understand, not why unit testing causes you to adopt them.
Mainly it reduces surprise. If you call an interface with implicit dependencies, you won’t know if why it’s breaking without debugging and making sure it sets up its dependencies properly. If you call a testable interface with explicit dependencies, you can mock out those dependencies to debug parts individually.
+1

Striving to make your code testable is almost always worth it. Someone might ask this guy to add some error handling to his code for example. :) Then he will find out that by writing code, however simple, that a "works on my machine" I.e. is proven to work in a single happy path context is painful to change. Writing code that runs in multiple contexts (composed as an app or decomposed for testing) is intrinsically more easy to work with and change.

Put another way, if your code is very difficult or complicated to unit test, you've probably abandoned best practices for the language you're writing in somewhere along the way, in the name of expediency.
The exercise of writing debugable and testable code is often worth more than the unit tests.
Functional Code with no side effect should be unit tested. Integration Code which glues various components together should have integration tests. If you feel like you need unit tests but have to create too many mocks, you have merged functional and integration code, separate them out.
Unit tests are insurance for later refactoring and library upgrades. This let's you avoid premature abstractions as you can easily swap out lines of code and verify you didn't break the app. This is especially important when you aren't the person doing the future refactoring.
Tests are insurance for refactoring which doesn't change the interface that is being tested.

Refactoring usually changes interfaces. Things are factored differently. The clue is in the name.

The higher up the stack your test is, the more insurance it gives you for refactoring. The lower downs the stack it is, the more likely it is to be thrown away or heavily rewritten after refactoring.

> Refactoring usually changes interfaces.

No, refactoring shouldn't change public interfaces. The very definition of refactoring is rewriting code without changing interfaces.

> Things are factored differently.

internally

> In computer programming and software design, code refactoring is the process of restructuring existing computer code—changing the factoring—without changing its external behavior.

https://en.wikipedia.org/wiki/Code_refactoring

You got the definition of refactoring wrong, please get it right, it's important. If you are breaking a public API, you are not refactoring anything.

Any piece of code meant to be private shouldn't be unit tested at all, only the behavior of a public interface.

Now internally you might call a third party lib, but that third party lib is then a separate "unit" itself.

I don't like the term "unit" because it's yet another word that is easily misunderstood and lost its original meaning with time.

unit testing should really mean "public interface behavioural integrity testing" or something like that.

(comment deleted)
People expose too much of their code as a public api. The public interface should be small, and that's what the unit tests should test against.

If users should not access it directly, you don't have to unit test it directly, you test them indirectly via the public interface.

(comment deleted)
What is external behavior? Behavior of the user interface of the program or behavior of some other code? What is external?

The term "refactoring" is commonly used in a way which includes changing of public interfaces. Random article, which even cites a book, agrees: https://thoughtbot.com/blog/lets-not-misuse-refactoring

If you're developing a library, then refactoring shouldn't change public interfaces. If you're developing an application and you own all the code paths to the code, then refactoring could change public interfaces, as the external behavior here would be the UI.

If you literally agree with the "refactoring shouldn't change public interfaces" then we need a new word for "code improvement which doesn't change external behavior, which can mean UI", which is the more commonly needed term.

And then perhaps we could agree that "code improvement often changes public interfaces" and how this relates to unit tests.

Exactly this. It's mostly lost on engineers that unit tests are usually testing at the layer that changes the most anyway - though the pain is felt once any real refactoring effort begins.
Unit tests are not a goal, they are a tool. Striving for 100% test coverage is nonsense, not testing your software at all levels is bad. Middle ground and moderation are where it's at, not a black vs white choice. Just like every other tool you should understand it's strengths and weaknesses and you should apply it properly, not dogmatically or it will bite you.
> Striving for 100% test coverage is nonsense

Tell that to SQLite guy.

Something like sqlite can actually be unit tested to 95% or so. If you stretch the definition of 'unit test' a bit (don't mock i/o).

Try that with a networked application that takes user input though...

Mocking networked services is something very much worth doing because you can then check you’ve set timeouts correctly, handling incomplete or junk responses gracefully etc. Those are the kind of hidden problems that can bite you on production deployments.
You can mock networks all you want and you'll still cover only what you can think of.

It will always break on the user's internet, because it's too diverse to predict.

Doesn't mean you can't have some networking unit tests, just that you shouldn't believe in them too much.

Edit: you said services. You thinking of server? I'm thinking of clients.

"mocking networked services" is exactly what you would do when testing clients.

And it doesn't have to be a static mock. It's not too hard to inject a fuzzer in your mock service response, although that's probably left to a separate testing routine, and not part of your unit test setup. But if you have no mock for your network service, you can't fuzz it either.

Striving for very high test coverage seems like exactly the kind of thing you want for your database infrastructure.
And that's exactly why you need less tests in your project that uses a DB: there's no need to test the DB because it's covered by its own tests already.
Interactions with your DB are often the most fragile piece of your code, because there's an impedance mismatch between the language you're writing and SQL. Some languages/frameworks abstract this more safely than others, though.
Exactly, though I believe there's still a thin line between testing the interaction, and testing the db itself. Just like, the difference between testing some code, and testing the language itself.
Interaction, in general, is where many, if not most, errors lie. Unit testing verifies that things work in isolation. But if you code up your unit tests for two components that interact, but with different assumptions, then the unit tests alone won't do you any good: X generates a map like `%{name => string()}`, Y assumes X generates a map like `%{username => string()}`. Now, hopefully that won't happen if you're writing both parts at the same time, but things like this can happen. Now your unit tests pass because they're based on the assumptions of their respective unit of code, but put it together and boom!
TBH

SQLite is suitable for 100% coverage.

A lot of application code or workflow style code is hard to reach 100% coverage as they are rarely triggered.

The rarely triggered code is exactly where you want unit tests.

That's an opportunity to describe, in code, what that path is supposed to do, and then make sure it does it.

And yet they had bugs and could lose data.

Which shows 100% unit test coverage is not better than spending that time in other kinds of tests.

unit tests don't account for timing-based effects and you generally can't test for ACID properties.
You should definitely watch this presentation on SQLite exploits.

SELECT code execution from using SQlite - DEF CON 27 Conference

https://www.youtube.com/watch?v=HRbwkpnV1Rw

Don't get me wrong, it's a great product and I use it often, but 100% test coverage does NOT equal 100% safe.

Yeah, but those QA dashboards monitored by management....
Exactly, the 80-20 rule also applies to unit tests. I don't have 100% coverage on big projects, but everything I write that's meant to go in production is in TDD anyway, so there's always enough tests to prevent a junior from breaking my stuff, and I save a lot of time because thanks to TDD I don't need to manually test much, and most of the times not at all, I just wait for user feedback: it's always much easier to have code working in real conditions, if it already works in test conditions, not the other way around.
there is real world research that actually shows that the 20/80 works in unit tests, the last 20% hardly catches any issues or contribute very little to quality
The benefit of 100% test coverage is that there are no more discussions on what to test and what not. When in doubt, test it. In larger groups of developers there are otherwise ongoing discussions if A needs to be tested or not. I have seen culture wars around this, from people who don't want to test and are in the eyes of others always testing not enough and vice versa. Especially with a diverse development force with different ages, seniority and cultural background.

It's often easier to just aim for 100% test coverage instead (with excluding some categories of files).

EDIT: I would not and did not start with 100% unit testing. But if there are ongoing culture wars and discussions didn't lead to a workable compromise, 100% test coverage worked for me and after some days test coverage was a non issue.

Even with 100% coverage, that doesn't mean you've found every bug that can possibly be found with unit tests. Your tests could always cover more inputs, more situations, etc.
No, you can't find bugs that you can't think of.

Property based testing and random values in unit tests find lots of bugs you didn't think of though.

> you can't find bugs that you can't think of

Rather, you won't find bugs that you choose not to think of because you've let the "100%" number lull you into complacency, even though you know it's 100% of lines/branches, not 100% of inputs.

Yes.

My problem in 40y of programming is still making bugs and those I make come from not thinking about edge cases or from wrong assumptions and not from being lulled into writing tests to meet a 100% number.

But personalities differ and if being lulled into security by writing towards a 100% number is a problem for you I would be careful, I totally agree here.

I agree that fuzz testing+linting can help you. However from my persective lower level tests help you to build trust about the software you're releasing.
This is dangerously close to not understaning what you are doing. _Thinking_ what to test has a benefit of making you think, not just cargo-culting.
Obviously you need to think about how to test. Usually this leads to finding omissions in your code adding edge cases.
Rule by diktat is a recipe for demotivated staff.
Ongoing culture wars are a recipe for demotivated staff.

Perhaps I am wrong, and I would not start with a 'diktat' for obvious reasons.

As a manager, you didn't have discussions about the level of necessary code coverage? Would be interested on how you managed unit testing without 'dictat'. How it would fit into integration testing and explorative testing. What level did developers in your deparment usually find "adequat" ? If you considered it too low, how did you raise test coverage as a manager without defining a coverage level?

"larger group of developers" is the phrase that caught my attention. Humans don't scale well. This is where microservices do become attractive. This service is owned by a small team, and that team makes these types of judgements. It may be very different from how other service is owned and maintained, and that's ok.
From my limited experience you get cross team discussions about unit testing, especially if one microservice has too many bugs in the eyes of other teams giving development a bad reputation or making working with a microservice hard. Especially if it breaks with releases and other teams get paged.
Yes. you move the people don't scale well issues to multiple teams don't scale well
I like thinking about the trade off between a simpler rule that is mostly right vs. decisions require judgement and consensus. I think the simpler rule is usually the better side of the trade-off.

But in this case I think the cure might be worse than the disease. Tests for plumbing code often end up being brittle tests of methods getting called on mocks in the right order. People will notice that these require a lot of toil to keep them running as code changes while providing very little benefit in avoiding mistakes. People will rankle at being told that they must write these tests, which they can see are a waste of time.

I've done it both ways. I'm much happier with my work when I'm not trying to write tests that are tedious and don't seem to provide any value, in order to hit an arbitrary coverage metric. I suspect my teammates feel the same way, so on teams where I have input into the decision on this, I do not advocate for 100% coverage. It does make it harder to have the discussion of which tests should and shouldn't be written, but I think it's worth that cost.

Yes I have seen bad unit tests very often.

Writing good testing code is harder than writing business code. Especially junior developers struggle with this, most often because many companies write not enough tests to learn writing good tests.

And if you're in an environment, where this is a non-issue I think thats great. Don't fix something that doesn't need to be fixed.

Yup. The debate over unit testing, being political, is a far bigger impediment to progress than the actual tests, which are a technical hurdle. It's essentially the same reason for linters and auto-formatters.

It has a side benefit that it forces devs to write testable code, which inclines them to reasonbly factored code.

100% test coverage is pretty easy to game as long as the metric is known. Just exercise all paths and write as few assertions as you can.

I'd prefer <100% coverage plus discussions about what to test (and how) much more than working with a test suite built on the wrong incentives.

If you are someone who games metrics for his benefit or hire people who are gaming metrics for their benefit, I assume yes, this metric is very easy to game as are most metrics. Metric systems are not cheater proof.
> just aim for 100% test coverage instead (with excluding some categories of files).

That's where the 'gaming' comes in.

The tests start just going through lines without hitting a single expect statement.

The ignore files start becoming battlegrounds in the PRs because people just exclude half the damn project.

We just have a simple rule... if you wrote code, you have to write coverage for it. If it breaks and your test doesn't catch the breakage, the bug fix goes back to you. Some people will ask "but what about what I'm working on now", you'll have to communicate that you feel your previous work was far more important.

> the bug fix goes back to you. Some people will ask "but what about what I'm working on now", you'll have to communicate that you feel your previous work was far more important.

this feels punitive, especially in the eyes of management. unless you're in a safety critical area where fully testing every code path is a hard requirement, people will eventually write bugs.

i'd rather work somewhere that recognizes defects occur and has a fast iterative process to push out new changes rather than one based on shame for having written a bug.

> has a fast iterative process to push out new changes rather than one based on shame for having written a bug.

That is the fastest most iterative process we have found so far... as the expert on the original code, you are able to deliver the best outcome.

You're not being shamed for writing a bug, you're being shamed for not testing your code.

This argument, that it avoids discussions, does make sense but only if you're in a team where discussions tend to be a waste of time.

When my colleagues are knowledgable and open minded I would embrace every opportunity to have a good discussion.

> It's often easier to just aim for 100% test coverage instead (with excluding some categories of files).

Congratulations, now you have a war over which categories of files are excluded from the "100% test coverage" rule. ;)

I read this complementary one the other day, and one thing that is readily apparent to me is that a lot of people have a lot of different opinions about testing (move to system tests! more unit tests! regression tests!), but many are not asking the zillion dollar question:

What are you testing for?

This is critical because it basically gives you immediately what you should and should not test, and how. While mindless, dogmatic, metric oriented testing is a waste, testing with higher intent and purpose is extremely useful.

An example: test that something working on current vX also works on vA to vW, and when vZ is out, have the answer readily. Or that a biz feature fulfills the requirements. Or that someone not as well versed on intricate details of your piece of ownership will be confident in that piece still working after a simple fix when you’re on vacation. It can be one, some, but probably not all.

With that in mind, what to test, what doesn’t make sense to test, and what to test against becomes more clear: should I mock this? or should I run it against some staging environment? Should I perform (yikes? not!) manual testing?

The answers are highly dependent on the piece of code being tested.

Tests are here to help you answer a question, if you aren’t sure what the question is then your tests will miss the point.

https://flak.tedunangst.com/post/against-testing

I feel like a lot of unit testing is just another form of bikeshedding. It's easily understood, everyone can talk about it, and you can spend a lot of time on it with no clear goal but feel like you're getting something done.
Actually it is pretty common to have 100% coverage with some extra redundancy too (where some things get accidentally covered multiple times). Striving for 100% is indeed nonsense, but having 100% coverage is usually accidental in clean code that you want to work, and merely a by-product of TDD.

I strive for working code. Sometimes I miss something in the TDD cycle and don’t have 100% and it is that which usually comes back to bite you.

I have never found 100% test coverage has bitten me, dogmatic or otherwise.

If it didn't catch any bugs, either during initial development or through later changes, then it bit you via wasting your time. I don't think it's fair to say that having tests necessarily makes the code under test any cleaner.
That heavily depends on the size of your codebase and perhaps also the language you are writing in. Writing in C++, for example, I often have switch statements in the form of:

  switch(type) {
  case X:
    ...
  case Y:
    ...
  default:
    throw InternalException("Unsupported type!");
  }
Now if all goes well the default case will never be covered. At some point I thought "why have this code if it's not supposed to run; let's rewrite this so we can get 100% code coverage!", and I ended up with the following code:

  switch(type) {
  case X:
    ...
  default:
    assert(type == Y); 
    ...
  }
Now we can get 100% code coverage... except the code is much worse. Instead of an easy-to-track down exception we now trigger either an assertion (debug) or weird undefined behaviour (release) when the "not supposed to happen" inevitably does happen because of e.g. new types being added that were not handled before.

Is worse code worth getting 100% code coverage? In my eyes, absolutely not. I think good code + testing should be able to reach at least 90% typically, likely 95%, but 100% is often not possible without artificially forcing it and messing up your code and/or making it much harder to change your code later on.

Why can't you have a test that checks if the correct exception type is thrown on invalid input? The exception is part of your API too.
This behavior occurs in internal functions and is not triggerable by the user. The only way to trigger this behavior would be to create unit tests that test small internal functions by feeding them specifically invalid input. This is possible, but I would argue this falls under "dogmatically trying to reach 100% code coverage". Testing small internal functions adds very little value and is detrimental to a changing codebase. After adding these tests every single change you make to internals will result in you needing to hunt down all these tiny tests, which adds a big barrier to changes for basically no pay-off (besides a shiny "100%" badge on Github, of course).
As always, I think the answer here is more along the lines of "it depends." It's not that uncommon of a task to make an existing function more performant, and a well thought out test suite makes that leaps and bounds easier even for small, internal functions.
It's arguable that this is a programming bug an not really recoverable, so throwing doesn't make much sense.

You can be defensive to various degrees about assertions:

1. You can just use assert() to fail in Debug and do nothing in Release. 2. You can be more defensive and define your always_assert() to fail in Release as well. 3. You can double down on the UB with hints to the compiler and provide assume(), which explicitly compiles to UB when it's triggered in Release (using __builtin_unreachable() for example).

About the organization of the if statement: I agree that the former is better, I would use assert(false) though.

Indeed it is a programming bug - but programming bugs happen. In my experience writing programs as if bugs will not happen is typically a bad idea :)

Throwing an exception here is basically free (just another switch case) and gives the user a semi-descriptive error message. When they then report that error message I can immediately find out what went wrong. Contrasting with a report about a segfault (with maybe a stacktrace), the former is significantly easier to debug and reason about.

assert_always would provide a similar report, of course. However, as we are writing a library, crashing is much worse than throwing an internal error. At worst an internal error means our library is no longer usable, whereas a crash means the host program goes down with it.

__builtin_unreachable() is your friend.

Better yet, omit that default case, so that in the future when you do add a new value to the enum, the compiler will warn you and force you to add a new case.

But I agree with your general thesis that it's just not worth getting to 100% coverage.

> "Striving for 100% test coverage is nonsense"

100% coverage of what exactly? Tests that go through all your lines of code without testing any of the logic, is useless. If you want to be thorough, you need to do mutation testing, which is a system that tests the quality your unit tests by mutating your logic (changing a > for >=, a + for -, etc) and then expects at least one test to fail. If no test fails, that piece of logic wasn't tested.

Without that, it's entirely possible your high code coverage doesn't actually test anything meaningful. Also, this sort of logic is exactly the kind of stuff you want to unit test. All the standard plumbing boilerplate code is not something that needs to be unit tested. The logic does.

and it's not just that, for example branch coverage only says that you branched but not how, a complex branch might need more than one test to be fully, or decently, tested.
Right, essentially you have to be aware that you are testing the state space the code might end up in, which is very different from just hitting every line of code or every branch.
On that note it is a great tool during development to get a piece working without connecting it to the broader application. Test driven development gives a nice debugging context that is easier to work with. The code coverage and regression part comes as a nice bonus feature.

I’d also like to add that if you contribute code to an open source project it is extremely beneficial to have iron-clad unit tests. Since there is so many devs it would be easy for someone to accidentally break something you fixed already.

And like other tools their importance is part of the entire tool-set. In many shops tight schedules, management by Product managers or people who are too removed from code cause you compromise every other principle of responsible sane coding. When this happens, unit tests are your only shield from doom. If everybody knows and allowed to write sane, good code with reasonable time to build it, the unit tests are nice to have but not a must
this is our take on it: https://eng.rekki.com/unit-testing-at-rekki/t.txt

TLDR:

    * test your core, make sure your core is strong
    * don't test your http api
    * don't mock
    * don't test writing and reading from the database
    * don't complicate your code to make it testable
    * ... unless you deem fit
If you don't do 2 you may as well not test at all. You may do everything else and still fail your end APIs. Your users don't care about your core or mocks. They want end APIs to work

The rest just seem arbitrary. Can you make a change and be confident it works ? The last point sums up everything. "Use your best judgement"

"don't mock"

How are you meant to write a unit test for a class without mocking out external dependencies? Wouldn't that make it an integration test?

Not the OP but I count integration testing as testing integrations /between/ systems - wherever your code depends on something outside your codebase. You can mock this for unit testing.

Don't mock things that are already in your codebase. Use the actual object.

Common argument against this I've heard is "But then when something goes wrong it is harder to figure out where the problem is" - I have never actually experienced this myself, but I have, very often, experienced being reluctant to do any refactoring because I'd have to rip up all the unit tests because they are testing only implementation details

You definitely have some strong opinions about testing. I'd suggest being more specific so your guidance is more clear. "people who test what they think is appropriate" is really subjective and makes it seem like there's two camps: people who "get" the author's perspective, and those who don't. I've tried the "do" and "don't do" approach, but that's not enough information usually. Teach by examples. Lots of examples. Calling things BS isn't going to change someone's mind. I'd also re-enforce that these practices are for your codebase. Every project is different and has different challenges. There's a reasonable counter-example for each item in your TLDR, and "unless you deem fit" doesn't feel like it gives developers leeway given how strongly you state your opinions.
> There is no formal definition of what a unit is or how small it should be, but it’s mostly accepted that it corresponds to an individual function of a module (or method of an object).

And there-in lies the problem. Remove the idea that the unit is a single method/function.

I subscribe to the idea that a unit is a unit of functionality. Nothing to do with the code implementation.

Only mock where you're reaching out outside of your codebase (filesystem, network, operating system (time, for ex.))

You can still do unit tests for individual functions when you need to work on a complicated algorithm, but those functions should have no dependencies or side effects - pass in all the data you need

One interesting thing that is easy to notice about all of the examples of in the article is that they are absolutely infested with objects.

I don't have anything against objects, per se, but I think they tend to make unit testing much more difficult to accomplish. The closer your code resembles pure functions, the easier it is to do dependency injection and unit testing.

Yup, this is very true. As long as you return something deterministic, unit testing is easy.

It's where you need to handle mutable state with objects that things get trickier.

Unfortunately, these are exactly the places where you most need tests.

I'm a big fan of constantly returning things rather than holding state in objects, for specifically this reason.

A basic issue of encapsulation: objects shouldn't rely on the mutable state of something else, but only on their own.
Agree. To add to this, many unit tests that you might have to do become obsolete with a strongly typed functional language. At that point you’re basically only integration testing the API boundaries / external interfaces.
There isn't pure functions the moment you touch any kind of IO.

Plus the same problem arises with modules instead of objects, which traditionally are even harder to customize.

> There isn't pure functions the moment you touch any kind of IO.

You can get pretty far with good abstractions and dependency injection. Go's io::Reader and io::Writer interfaces are a great example of this. The resulting functions aren't pure in a technical sense, but they're pretty easy to unit test none the less.

> Plus the same problem arises with modules instead of objects, which traditionally are even harder to customize.

Maybe you could elaborate. I really don't understand what you mean here.

From what I understand, modules just scope names, they don't maintain state. I don't see how they have the same problems as objects.

> You can get pretty far with good abstractions and dependency injection

Which goes back to the article's point of having to write code that is unit test friendly.

Now architecture decisions have to integrate interfaces that wouldn't be needed otherwise.

> Maybe you could elaborate. I really don't understand what you mean here.

Modules keep state via global variables, module private functions and the surface control that they might expose via public API for the module.

Additionally on languages that support them, they can be made available as binary only libraries.

> Which goes back to the article's point of having to write code that is unit test friendly.

> Now architecture decisions have to integrate interfaces that wouldn't be needed otherwise.

You're not wrong.

But in the context of functions, that doesn't seem to me to be particularly onerous. If the worst I'm forced to do is change the type of my parameters to an interface instead of a concrete type, that seems like a pretty small price to pay for easy testability. Certainly a much smaller price than the examples in the article.

You are assuming that interfaces exist as language concept.

Imagine doing unit tests for a C application, where modules == translation unit/static/dynamic library, thus you can only do black box testing.

Now one needs to clutter it with function pointers everywhere, or start faking interfaces with structs, just for the benefit of unit tests.

And with static/dynamic libraries than one might need to start injecting symbols into the linker to redirect calls into mocking functions.

All just to keep QA dashboards green.

That's how a lot of great C code is written anyway. A C library should abstract out logging, allocation, and IO so that the client code can change them out if need be.

The fact that it makes unit testing easier is just icing on the cake.

Having written tests for enterprise C code, I wouldn't call it a great experience, rather something I am glad not to ever repeat again.

Mainly due to the linking hacks and low level debugging sessions required to mock all necessary calls.

Plus that was just an example, there are plenty of languages with modules and binary libraries.

I mean, that's why great libraries don't make you do that. There's a lot of crap libraries.

The libraries dependencies should all be indirected through whatever context struct you pass to all your calls.

Agreed, and this goes back to the initial thread that just because a language is more focused on functions it doesn't make testing automatically better, unless it was written with testing friendliness as part of the requirements.

Sadly not all code is great.

For C, I've found it's not a test friendliness thing though; the great C libraries were doing this before unit testing made it's way into their codebases. They dependency inject IO, memory allocation, and logging because they have no idea what you as the end user are going to be using for those. So you pass all that in on an env struct when you initialize the library.

You probably want it rigged up to your own logger instead of just blindly writing to stdout. You probably want the library's allocations tagged somehow on the heap so you can track down memory leaks. You probably don't want it doing IO directly, because of how many different way there are to do IO.

It's all more a function of how incredibly varied c envs are, than design for testability. It just happens to be very testable as an aside.

Yes there is. What you do is have don't put any IO calls inside your pure functions, but rather pass in their results as parameters.

Keep the impure code and the pure code separated.

Beautifully said, practically impossible unless the language imposes it as programming model and you have 100% control over the complete source code.
Mock frameworks make it trivial.

  Foo foo = new Foo(mock(Bar.class))

  foo.a(x,y,z)
Not sure what the issue is there really.
> Mock frameworks make it trivial.

In my experience mock objects can be brittle. A few sprinkled in judiciously can be ok, but once the density gets high enough, it starts to feel like the test becomes decoupled from the actual code it's supposed to test.

> The closer your code resembles pure functions, the easier it is to do dependency injection and unit testing.

If the only thing you inject is data, can we still call that "dependency injection"?

> If the only thing you inject is data, can we still call that "dependency injection"?

I suppose that's a philosophical question.

Probably the 2 most common functions I 'dependency inject' are rand() and time.now(). I feel like they count, but you might not.

You're one sentence away from discovering Common Lisp ; )
(comment deleted)
I mean, if you pass a HOF to some other function, then that is also a dependency.
Correct, but I haven't seen it happen often in practice. I mean, pretty much every project uses HOF, but few have many of them.

I also tend to avoid HOF when I can instead pass data around explicitly.

By whom? Compared to what?
Compared to integration testing and end-to-end testing.
My own take on this is that it is hard to crystallise why or what a "unit" is. My cop out is it comes down to experience - once you've done this enough and solved enough problems and worked on enough teams, you'll get an intuition on this as it is more art than science.

I find it to be some mixture of importance and complexity, while always balancing against the single responsibility principle. A simple `average` function might be trivial but if it's important to your business logic you probably want to test that separately, even if it is nested within a "unit".

I find that following some iteration of "functional core imperative shell" helps here as it helps keep your core business logic to being data transformations and transformations on data are easy to test and their concerns are easy to reason about.

This then helps me reason about what is "implementation" and what is a contract/interface which should be tested robustly.

I guess really the art of writing just enough unit tests is to identify the seams and boundaries of your abstractions in your codebase, and potentially accepting that business seams in your codebase may be different from the seams of your actual software domain -- the latter being possibly more granular.

Unit Testing, yes, it can be a waste of time. Depends on what you're doing. Unit Testing fails when you sink more and more time into trying to make a test for something because 'duh, unit test everything'. Fact is some code changes a lot and some code doesn't change much. Some code is also hard to unit test and some isn't. The intersection between code that doesn't change much and code that's hard to unit test should NOT be unit tested, especially if another form of testing works better. There's just no need to sweat over a test that wont run enough to justify the work that went in to writing it.

The issue here is developers don't have a sense for economics. Diminished returns, marginal utility, and opportunity cost should be studied by ALL.

Unit testing reveals latent defects, defects that can't be triggered by the system as it currently exists. Each such defect is a problem waiting to pop out in the future, as the system changes and the latent defects become exposed.
Yes but discovering those hypothetical defects is usually less important than discovering the actual, currently present defects.
We initially only had integration tests, because many people think they're better. I get it: itests use the real plumbing, so they're more representative of your runtime. But they're slooooow -- especially the tests that involve the DB (which is most of our itests).

So we started adding unit tests. Utesting code that wasn't written for utests is painful: you often need to choose between refactoring or just patching the hell out of it. The latter is highly undesirable, since it leads to verbose tests, failures when you move a module, and the inability to do blackbox testing.

But utests encourage our new code to be clean and readable. We've found that functional programming is much easier to test than object-oriented, and is easier for engineers to grok. We just sprinkle a little dependency injection and the whole thing works nicely.

Itests have their place, but utests lead to faster feedback and more readable code.

Weird that you started using a functional approach, noticed that it’s easier to unit test, and drew the conclusion that unit testing is what led to more readable code. Consider that functional code is the source of readability. Also we don’t typically call it “dependency injection” in the functional world
You're absolutely right: functional code is the source of the readability. But writing unit tests incentivizes engineers to keep things functional.

What's a better term than "dependency injection"? What should I call an argument whose default is always used in production code, but is there to make passing a mock easy? I'm not trying to be snide -- I'm genuinely curious.

OT: Good Old Neon is a fantastic piece of writing.
I always just called it a "default argument"
I think this is part of the problem.

Unit tests are an easy path to fall down, because they're clearly easier to setup, to write for, require less effort to maintain, execute more quickly.

But you don't realise their significant downside until after you attempt a major refactor - you begin to see that unit tests are testing at the layer that changes the most anyway.

I tend to mentally divide code into roughly two types: "computational" and "plumbing".

Computational code handles your business logic. This is usually in the minority in a typical codebase. What it does is quite well defined and usually benefits a lot from unit tests ("is this doing what we intended"). Happily, it changes less often than plumbing code, so unit tests tend to stay valuable and need little modification.

Plumbing code is everything else, and mainly involves moving information from place to place. This includes database access, moving data between components, conveying information from the end user, and so on. Unit tests here are next to useless because a) you'd have to mock everything out b) this type of code seems to change frequently and c) it has a less clearly defined behaviour.

What you really want to test with plumbing code is "does it work", which is handled by integration and system tests.

This. Making the distinction between the two is huge. Save time and money testing the right pieces of a codebase.
I've seen this concept called by many names including CQS[0] and Functional Core, Imperative Shell[1]. I'm just leaving this comment here for those that are interested in reading more.

[0] https://en.wikipedia.org/wiki/Command%E2%80%93query_separati... [1] https://www.destroyallsoftware.com/screencasts/catalog/funct...

Functional / imperative doesn't exactly map on to these two concepts. "Computational" is often imperative and integration code isnt always imperative (a lot of react code would fit in this box, for instance).
"Computational" code that isn't by the vernacular definition of "functional"--and you can write functional code regardless of programming language--is something of a red flag to me.

Operate only on your inputs. Return all of your outputs. No side effects.

I think OP meant that functional code is inherently imperative under the hood.
Sure, but "functional" code, in the vernacular, means a rather less specific version of that.

You can, after all, write "functional C". (It can be hard, though.)

I agree, but if you watch the linked screen cast you can see that its just Gary Bernhardt's take on Hexagonal/Clean/Onion Architecture.

The idea that your business logic should be isolated from external dependencies (in his case, by making the code (pure) functional). That makes it easy to unit test the business logic, and your integration tests should be minimal (basically testing a single path to make sure everything is talking to each other).

This is adapting the structure of your codebase to the capabilities of unit tests.

It has advantages but it's an expensive waste of resources if you have cheap, effective integrarion tests.

Cheap integration tests is usually an oxymoron (when cheap refers to the tightness of the developer feedback loop).

Gary was coming from the land of Ruby-on-rails where a full set of integration tests could take hours. In that environment, structuring your code to enable easy testing of complex logic makes a lot of sense.

Likewise in a large enterprise environment, where integration testing across a (usually messy) set of interconnected dependencies is a pipe dream.

It's true that over-architecting is something to be wary of, but as usual, there's no one-size-fits-all answer.

It's cheaper to have a TDD test that takes 15 seconds to run and launches into an embedded kernel than it is to re-architect your whole system.

It doesn't matter if the whole test suite takes hours. CI servers don't need to be supervised.

One of the benefits of writing tests is that it makes it painfully obvious which parts of your codebase are poorly architected. Difficulty in writing tests is a code smell.
That's because unit tests couple tightly to your code. If you're trying to couple something additional to your already tightly coupled code it's gonna be painful.

It's a really expensive way of discovering that you wrote shit code.

I do like "abstract" and "concrete".

Abstract code solves made-up problems, while concrete code solves real ones. Normally the best way to solve a real problem is by rewriting it as a series of made-up problems, and solving those made-up ones instead.

The made-up problems don't need to be pure computational. Instead, if you restrict them to pure ones, you'll lose a lot of powerful ones. They also don't need to fit functional programming well, but there is no loss of generality on imposing that restriction.

Also, the more abstract you make that code, the less they'll need changing and the better unit tests will fit. At the extreme, once debugged they'll never change. Instead, if your needs change too much, your concrete programs will simply stop using them and use some completely different ones.

I think the problem with this line of thinking is that, most often, the difficulty lies exactly in rewriting the real problem into the made-up problems. So, to have useful tests, you need to check if your made-up problem solutions actually solve the real problem, which is difficult to express in the first place.

For example, let's say you want to get some users from your DB in response to an HTTP call. We rewrite this problem in terms of crafting some SQL query, taking some data from the HTTP request to create that query. We can of course easily test that the code creates the query we designed that the query contains the right information from the HTTP request etc. But, if we don't actually run the query on the actual DB with the actual users, we don't really know if our query does the right thing, even if we know our code creates the query we intended. And, if the DB changes tomorrow, our very abstract code that parametrizes a particular SQL query will still need to change, so our existing unit tests will be thrown away as well.

This is the kind of plumbing code the OP was talking about, and I don't think you can reduce the problem in any way to fix this (especially if the DB is an external entity).

There's nothing abstract about that query. You can easily confirm it by looking how you described it exclusively by business terms. Instead, it's the most concrete component on your comment, and it's not prone to unit testing in any way.
This is always a fun corner of programming terminology to me.

A ton of dense, mathy code like hash computation, de/serialization, sin/cos computation, etc. is usually best implemented in a memory efficient C-style way but lends itself to be used in a very functional way; inputs and outputs without any retained state or side effects.

I think that subtlety is hard to articulate and gets lost.

Yes! I do something similar which is sometimes referred to as functional core imperative shell. My goal is to put as much code as possible in the computational/functional part. This part is easy to test since it's pure. The remaining plumbing/imperative part has much less code, less dependencies, and less logic, which as you say doesn't need unit tests anymore. It needs less dependency injection as well, which is a huge bonus.
You should still be careful that your pure logic is actually doing something by itself, rather than just massaging data from one external format to another external format.

A lot of code can be in this are where it is absolutely unit testable, but the unit tests are almost entirely useless, as the code only ever changes because the input or output types change, so the tests also need to change.

I think of this in terms of code that is 'authoritative' for its logic or not.

For example, a sorting method is authoritative - it is the ultimate definition of what sorting means. Also, a piece of code that validates some business rule defined in a document is the authority for that business rule.

But a piece of code that takes input from the user and passes it to some other piece of code is not authoritative for this transformation. The functionality of this kind of code is not defined by some spec, but by 'whatever the other piece of code wants to receive', which may be arbitrarily hard to define.

Depending on the complexity of the transformation, there may still be reasons to test parts of this code, at least to ensure that a new field here doesn't affect the way we transform that other field there, but often only small pieces of it are actually worth testing.

Wonderful description. In brief:

Unit test algorithmic code; use integration tests for everything else, i.e plumbing code.

There's a very controversial conclusion to this : some projects ought to have zero or close to zero unit tests.

I agree very strongly with this but a lot of people will be very unhappy with this idea.

I agree with this, I also admit that 95% of the code I write is plumbing code. (There is an art to making your plumbing nice).
The people that place a controversy on this can be safely ignored.
Yes I agree as well. Our company uses Spring to write banking software and there is rarely a case that involve purely logic that can be separated from its dependencies. I used to try isolating code into separate methods that took no dependencies but it just made the code harder to read. Now we just test invoking the grpc endpoints and include the db (with rollback) and it works quite well.
I would suggest making the business logic stateless methods ("functions") that take data records that are immutable passed between it.

That allows strict separation of all I/O from testable business logic.

If you can't separate pure logic from your I/O, it means you have a Russian-doll program that looks like:

readFromApi {

  doSomeBusinessLogic{

    writeToPersistence{

      ...
Instead of a pipeline like:

a <- readFromApi

b <- doBusinessLogic(a)

c <- writeToPersistence(b)

If you do things this way, you can always isolate your business logic from your dependencies.

The problem is that doBusinessLogic(a) is often entirely about transforming a into whatever the current DB accepts. Sure, you can write a test to check that b.Field_old == a["field"] , but this buys you very little. The real question is whether you should have mapped a["field"] or a["oldFields"]["Field"] to b.Field_old, and your unit test is not going to tell you that, you need an integration test to actually verify that you made the right transformations and you're getting the correct responses.

By all means, if the transformation is non-trivial, and it is captured entirely in the logic of this method, not in the shape of the API and the DB, then you should unit test it (e.g. say you are enforcing some business rules, or computing some fields based on othee fields). But if you're just passing data around, this type of testing is a waste of time (you don't have reasons to change the code if the API or DB don't change, so the tests will never fail), and brittle (changes in the API or in the DB will require changing both the code and the tests, so the tests failing doesnt help you find any errors you didn't know about).

While it's bad form to reply to your own post, I might add this is just what a function is in the large, but you're viewing your program this way.

a <- readFromApi ( Input x )

b <- doBusinessLogic(a) ( f(x) )

c <- writeToPersistence(b) ( Output y = f(x) )

You can also imagine that there are more than one lookup from the db or service calls as I/O in different parts of the pipeline (g(f(x) etc.), but it's always possible to have state pulled in explicitly and pushed down explicitly into business logic as an argument. It tends to make programs have flatter call stacks as well.

> The real question is whether you should have mapped a["field"] or a["oldFields"]["Field"] to b.Field_old, and your unit test is not going to tell you that, you need an integration test to actually verify that you made the right transformations and you're getting the correct responses.

So I would argue you don't actually have business logic then. Your service is anemic, and you have a data transformation you need to do. I definitely think that you should do an integration test for that.

Moving JSON -> Postgres or whatever is something that you absolutely still can test with the output of the DML statement by your DB library. It may be a silly test, but that's because if there's no business logic, it's a silly program _shrug_.

Wise words spoken before me:

>> Write tests. Not too many. Mostly integration.

Watch the boeing fall from the sky. (Developer missed that particular configuration in testing)
The amount of effort spent finding errors before you ship it has to be related to to cost of fixing errors including the consequences of the errors if they're found after you ship.

If errors in your system result in death, and if changes must go through an expensive and time consuming process to be approved, and then an expensive and time consuming process to be applied, you should spend a lot of time ensuring your design is sound, and your implementation matches your design. A good place for formal methods.

If you're writing server side code, and deploy takes 5 minutes, you can be a cowboy for most things that won't leave a persistant mess or convince customers to leave.

If you're writing client side code that needs to go through a pre-publication review, neither cowboy or formal methods is a good choice.

What if you're a libffmpeg or libsdl developer?
Where do you slot device drivers in that hierarchy?
This has been a problem for me with my quarantine project. It's little more than a CRUD app: get some data, download it, display it on the screen. There's practically no business logic to it; the entire project is wiring up various XaaS. By the time I mocked everything that needed to be mocked, I'd have put more effort into mocking than the project itself.

I test the parts that are actually mine as best I can, but most of my debugging consists of driving it by hand.

> By the time I mocked everything that needed to be mocked, I'd have put more effort into mocking than the project itself.

More importantly, that your app works with the mocks doesn't give you good information about weather your app works with the actual services.

What if you write code that isn't for a business? How does your workflow apply then?
business logic does not mean it has to be for a business. It's more like calling the pointy part of a spear the "business end". It's the part that does the job.
(comment deleted)
Business Logic is a euphemism. It doesn't mean literally business logic, it means the 'core functionality of your code.' When you design software, you typically model some real world process or system in the abstract. Business logic is the core problem of your model. You can also call it model code, or core functionality. It all means the same thing - it's the important part of your app.

Using the old Asteroids arcade game [1] as an example: The business logic is how many lives the player has, what happens when you shoot asteroids (they break up, or disintegrate if they're small), what happens when you reach the edge of the map (you wrap around the other side), what kind of control scheme there is (there's momentum in asteroids, you don't stop on a dime) etc.

1) https://www.youtube.com/watch?v=WYSupJ5r2zo

"domain logic" might be a better euphemism. Consider a library that encrypts text with AES-256. You might want unit tests that verify the IV, cypher block, plaintext and encrytped text (result) of that function. The method, "encrypt" might be your "business logic" that ought to be unit tested.
"Business logic" is just another name of "logic". E.g. something like "if X is even, then print 'fizz' otherwise print 'fuzz'" is considered business logic.
Same point being made in the blog post. I do recommend others to read the post though - good stuff.
Wish I could upvote this more than once.
THIS....

i unit test business logic since that is the core of the application and MUST work as expected.

i'm not going to unit test a link that someone clicks on goes to the page they expect.

My thoughts exactly. Unit tests are a huge help in computational-heavy portions of a project and are easy to write. The other areas of a project don't benefit as much and the tests are harder to write and keep maintained.
This kind of categorising I've always found to be orthoganal to what should really be the measure of "does it deserve a [unit] test?" . I believe the correct way to assess how much (if any) automated testing at whatever level is decided only by how valuable that thing, and the inverse of the impact of that thing going wrong, is.

If you are writing on one shot script to transmute data from one format to another for say an upgrade, I don't care if you have unit tests if I am confident it has been manually tested to satisfaction. No repeatability, no regression requirement. There could and likely is value in TDD so tests might still be a thing if that is how you work. No objection there.

If you are developing the plumbing code that will ensure my system adheres to financial regulations and, if it were to break, land me in jail for negligence, you can be damn sure I'm demanding a test that will be run everytime that system is built/deployed.

I wrote unit tests >10 years ago for formatting a string for postal codes that I know are still run to this day on every commit because if they get it wrong there is legal recourse for the company that owns that system.

It's also super quick to fix and failing at build is quicker and cheaper than failing in prod, even without the recourse. That test took me all of 1 minute to write. Bargain.

> I believe the correct way to assess how much (if any) automated testing at whatever level is decided only by how valuable that thing, and the inverse of the impact of that thing going wrong, is.

Unit tests and automated tests are two completely different concept.

Vehemently disagree. Unit tests are subset of automated tests.
(comment deleted)
> I wrote unit tests >10 years ago for formatting a string for postal codes that I know are still run to this day on every commit because if they get it wrong there is legal recourse for the company that owns that system.

If it's critical for your business I'd categorize that as business logic, not plumbing code, well deserving of unit test coverage.

I don't really care for the distinction is my point. It's valuable and that's all that matters.
I really wish I had come up with this, it really neatly captures my experiences and how sometimes unit tests were really useful (Developing a (Benefit) Claims Engine which essentially did a bunch of complex calculations and then spit data out) whereas other times, unit tests just feel like a massive chore with mocks and similar stuff that add little to no value and certainly should've been at a higher level (integration or system tests) but the powers that be wanted coverage.
Absolutely. One other takeaway is "write less plumbing code". Write library code that simplifies your plumbing, and unit test that.
This is sort of what I've done with some success in developing games. Games in general are grossly under-tested, but there are a few good reason for that. Lots of systems can be effectively tested by just playing, and often it's tough to tease out as small of units for useful isolated testing as you would in other types of programs.

What I've been doing is writing as many parts of the game as libraries as is possible, and then implementing the minimal possible usage of that library as a semi-automated test. For instance, our collision system is implemented as a library, and you can load up a "game" that has the simplest possible renderer, no sound, basic inputs, etc. and has a small world you can run around in that's filled with edge cases. This was vastly easier than trying to write automated tests for 3d collision code, and you get the benefit of testing the system in isolation, if not automatically. For other libraries like networking, the tests are much more automated, but they poke the library as a unit, rather than testing all the little bits and pieces individually.

Computation can be seen as plumbing. I think what you mean by "computational" is complicated plumbing.
> I tend to mentally divide code into roughly two types: "computational" and "plumbing".

I agree with this and would go even further. Divide your code into "stateless" functional code and "stateful" objects code.

Original OO was encapsulating things like device drivers that did I/O--it didn't represent data.

If you don't interleave your stateless business logic with your stateful persistence, it's easy to mock "objects" that do the plumbing, and all the meat of the program is unit tests.

Fwiw, the DI model (Guice, Spring, etc.) in modern Java/Scala shops closely hews to this, even if people don't mentally categorize it as such.

> Divide your code into "stateless" functional code and "stateful" objects code.

IINM you are basically referring to the difference between static and instance methods in languages like C++ and Java.

Putting code that neither reads nor writes the object state and instance methods is a common mistake made in both those languages.

That said, both stateful and stateless code are good candidates for unit testing, especially when the code under test is a state machine, rather then just a data encapsulation mechanism.

Nah brah. (I'm gonna say "brah" because I'm feeling especially salty)

Your _program_ should have the flow of a function. At the architectural level, who-the-ef cares about about static vs instance methods in Java (I say as a person with 23 years of Java experience.) It has nothing to do with languages. You can do this in any language you want.

You want to have your inputs go through a process where you have (1) INPUT state transfer, (2) some computation F(INPUT), (3) some output and state transfer, or RESULT = F(INPUT).

If you do not have (1) or (3)--I hate to break it to you--but all your program does is burn CPU. If you don't have (2), your program does nothing at all.

The key thing with scalable systems is they manage complexity well. If you're at the level where you're worried about "static or instance methods", you're not dealing with how data changes in large systems at all. Those words are at the level of state within a language.

You need to optimize at the global systems level.

> At the architectural level, who-the-ef cares about about state vs instances methods in Java

Who-the-ef should care is anyone who has to implement or maintain the code. After all, the debate at hand is what is worth unit testing, which very much concerns the programming language and the actual implementation. Don't know about you, but I both architect the system and write the code.

> If you do not have (1) or (3)--I hate to break it to you--but all your program does is burn CPU.

I haven't written production code that doesn't have (1) or (3) in my 25 years of programming, so not sure who you are talking to here.

> If you're at the level where you're worried about "static or instance methods", you're not dealing with how data changes in large systems at all. Those words are at the level of state within a language.

You have to tend to this stuff at both the generic data processing and language level. Using a given language's constructs for differentiating between stateful and stateless code is an important part of making the code document itself.

Coding style matters.

> Coding style matters.

It. does. not.

If it did, PHP wouldn't be running half the world. Structure and systems matter.

> It. does. not.

OK 'brah', whatever works for you!

> If it did, PHP wouldn't be running half the world

PHP has a style guide, and there is such a thing as clean, readable PHP code.

https://www.php-fig.org/psr/psr-1/

I bet massive scale PHP based apps (like you know, Facebook) probably enforce style in their codebase.

I'd add that perhaps for this 'plumbing code', the way you describe it, gradual/static typing is a great solution.
> I tend to mentally divide code into roughly two types: "computational" and "plumbing".

I think of the "computational" type more as a "deterministic data transformation" type. That applies to transformations of any data whether text, images, or the state of a machine.

I think of plumbing as the movement of data without any transformation, or if a transformation occurs, it occurs at and abstracted layer that must be unit tested itself independently.

I completely agree, but it doesn't help me hit the code coverage goal foisted upon me.
The example is a straw man. He refers to a doubling in code size, but that's just because he's got hardly any code. In a real class, you still have one method (or two! or three!) on the interface but you've probably got 300 lines in the implementation. The only thing being "duplicated" is the external interface.

Might as well retitle this "Why I don't like the Interface Segregation Principle".

The units here are poorly designed - for example, I'd expect the LocationProvider to be responsible for choosing how to get the location, not the caller - and this makes them hard to test. The solution is fixing the design, not throwing out unit tests entirely.

The standard reference on this is http://www.growing-object-oriented-software.com/ .

This title is wrong. It's not the tool's or technique's fault.

Unit Testing is not overrated. It can have been overrated by some of us sometimes or most of the time, depending on who you are.