150 points · by Liriel · 9y ago · 70 comments
In the example, the tests now really care about how data is being retrieved from the database. Instead, I'd use an in-memory database (or even a Dockerized one). That would then also test that the right queries are being done, but you could still refactor the internals of UserServiceImpl (terrible name btw) and your tests wouldn't fail.
Mock testing essentially tests expected side effects. A more powerful concept is the use of pure functions wherever possible, so that your tests compare input/output pairs, instead of long, difficult to maintain and sometimes non-exhaustive lists of expected side effects.
Does anybody know how one can replace Services, Controllers, Presenters and other such imperative mediator objects with a more functional approach? I'm just speculating, but that should make test maintenance easier.
What I'd like to see is testing only the returned value of a function, as opposed to calling a void function and checking whether the injected mocks got the proper method invocations, i.e. whether the desired side effects occurred.
I'm not sure this correct this case. He mocks the repo. The interface for the repo cares about the intention, the implementation cares about the "how". If your creating a user, you always going to want a "add" to persistent store intention. You don't really care how the add to persistent store is done though, or what persistent store. You just care the service intended to do so.
I have an idea that you if your performing a command, you should mock. The whole points of a command is to coordinate subsystems to perform an action. So you need to check if the right methods were called.
If your performing a query you should stub or in memory db.
Compilation in strictest form of TDD is the first failing test that you run. Catching this has advantages, such as knowledge and contemplation of altered ABI.
Your interface refactoring could also originate from your tests. Alter the code in your test (even the mock interface) until it is clean at that usage site, and the compile/test run until everything passes.
Now it is true that some interfaces are more stable than others, and you can make a good argument that testing shouldn't be done at boundaries that are likely to be unstable.
A test should care about: input, "do something", output.
Then you can refactor the heck out of "do something" and your test (which is ideally documenting the use cases you need to support) doesn't have to change at all.
For me, preferring stubs (dummy implementations of your external dependencies), when possible/appropriate, is a good way to avoid "your test is just a repetition of which method calls your implementation makes":
http://www.draconianoverlord.com/2010/07/09/why-i-dont-like-...
(assuming the second part of that statement should have been "that your program will still be correct")
I'm back and forth on my agreement/disagreement on this one. One of the major purposes of tests is to have confidence in refactoring, but it isn't the _only_ purpose. Beyond that though, I'd say that unit tests probably aren't the right tool for the job when we're talking about refactoring. The purpose of unit tests is to verify that the unit of code is working in isolation. Integration tests are much better suited for verifying correctness when refactoring. Any good test suite should have a healthy balance of unit tests and integration tests. And, when I say integration tests, I mean whatever you want to call them -- tests that check the system as a whole.
I don't necessarily disagree with you though. Mocks aren't perfect, and they have their own host of problems. I've run into a number of passing tests that should have never been that way because of mocks. It happens. The best way to combat this is to use mocks more sparingly, and have feature tests for many of these cases.
I think integration and other coarse-grained tests are far more useful more often, and using asserts (which will cause these coarse-grained tests to fail, too) is a better pattern than "unit test all the things".
I'm working on a code base of about half a million lines at work. We have lots of functional/integration tests, but no unit tests, and the code (C++) is not designed for it.
To add unit tests, we would have to rearchitect a lot of the code.
Last year, as a side project, I took some of our code, rearchitected it, and added unit tests as a proof of concept.
Since I knew I would have to convince management (essentially justifying a lot of churn to add these tests), I had a simple rule:
Every change I make to add unit tests should have some value even if we never add unit tests.
This helped me focus on code changes that I could objectively say improved the code quality, and helped me reject changes that were "just for unit testing".
I've done this before. It's very easy to want to make all your function/method calls work the same.
To stop, I applied the following rule whenever I had to choose between making a function static or mockable: does this function's name completely describe its implementation? Small methods like "StringUtils::isEmptyOrWhitespace" pass this test: it's just going to check if the string is empty or only contains whitespace, and that doesn't need to have its implementation swapped out. On the other side, "ImageUtils::detectFacesInImage" goes into no detail about how it does the face detection, and definitely needs an interface to test against.
That said, it all depends. You might allow your users to pick which characters count as whitespace, I don't know.
> I think integration and other coarse-grained tests are far more useful more often!
Yes! Integration tests are the "main" tests. Unit tests are secondary. Use them when you need to debug why your integration tests fail.
http://blog.cleancoder.com/uncle-bob/2017/03/03/TDD-Harms-Ar...
DHH wrote an article with the title "test induced design damage", not sure if he coined the term.
I think there's a grain of truth there; it is possible, but not necessary, to mangle your architecture to enable testability.
The case that DHH was complaining about is quite interesting in itself; it was an architecture that Weirich suggested (https://www.youtube.com/watch?v=tg5RFeSfBM4) where the framework DB models (in his case Rails) are separated from the Domain Models, to allow you to 1) run your tests of the business logic faster (without spinning up a DB) and 2) decouple your business logic from your choice of framework.
I've felt the need for this factoring in my own code, but actually making it happen is tricky, since you lose a lot of the magic that makes your life easier (but that also couples every level of your architecture to the framework's concepts).
ML people are probably more knowledgeable, but their job is also often more like science than traditional software engineering.
J.B Rainsberger says it best: https://www.youtube.com/watch?v=VDfX44fZoMc
JD Rainsberger's proscriptions in particular sound like a recipe for creating a massive amount of test code, a huge maintenance headache and tests that are not at all realistic.
If you don't care much about covering large portions of the state space and your tolerance for defects is high, then I'm sure your claim about improved productivity is true.
My tolerance for defects is low, which compels me to try and cover the state space more - happy paths, unhappy paths, etc. I've tried doing this with integrated tests, and found it to be very difficult to do in a timely manner. When I switched to using DI, coding to interfaces, and using mocks across architectural boundaries, my ability to cover the state space went up, and my time to deliver code with few defects went down.
I think this is because often the code I care about exercising is limited to a small section of the call stack. In an integrated test, I have to set up too much state and have the machine do too much irrelevant work just to verify this small portion of the code. With DI, interfaces, and mocks, I can isolate just this behavior much more quickly.
That leaves coupling and maintenance. This is a valid concern in the mockist style, but I haven't found it to be a limiting factor in maintaining my code. I think it comes down to testing the right things. If you're using mocks to verify a contract between two objects, and you want to change that contract, naturally your tests for the contract will break. In that case, I think it's fine to just delete them and write new tests that establish your contract. This kind of approach isn't right in all situations, but mockist style testing has helped my write some stable code that would have been a real pain to test due to external dependencies otherwise.
EDIT: That is not to say that your tolerance for defects is high, but rather that productivity is relative to your goals. Sometimes the time spent preventing defects and keeping maintainability high isn't worth it if the repercussions don't translate to dollars and cents.
I think it comes from a pretty decent practice of coding from the tests outward. However I'd argue the long term value of many of those tests is minimal.
But as long term protections against regressions, such tests are less valuable than more coarse-grained integration tests.
And what is not clickbait—
Need we ask anyone to tell us these things?
I know it's not done to be offensive, and maybe defended by saying "we're just honoring their culture" or something like that. It's just kind of awkward, can't we agree on that at least?
To be clear, I grew up in Cleveland and have been listening to a comparable debate my entire life: https://en.wikipedia.org/wiki/Cleveland_Indians_name_and_log...
First, DI is simply the least subtle for of IoC available. When all else fails, you can always rely on DI. But, this is something languages should be looking to help developers with. Elixir, for example, supports IoC as part of the language, and is much more elegant than DI [1]. When monkey patching is available, this is also a possible solution (easy to abuse, yes, but suitable in simple cases). Functions as first class values can also help (instead of passing a clock around, you can have a SystemClock.Time func that you can override in your tests, which is similar to what Date.now() is in javascript).
But, perhaps more importantly, and as much as I tried to deny it, integration tests are absolutely and totally worth the trouble. If you unit test two parts independently, you run the very real risk of having them pass under test, but fail once deployed. I've seen more production downtime caused by incorrect assumptions between services than anything else.
Also, lately, I've been writing more and more fuzz tests. I'm probably not very good at it yet, but I think for the couple of projects we did it, it's been a worthwhile effort (moreso when we started...they barely catch anything now since we're all coding much more defensively).
Unit tests are meant to be fast, and quick to isolate the failing code.
Your testing feedback might be quicker, but quickly getting useless information (ie. your implementation changed) is just as bad as slower tests, because you need to fix the test, recompile and again before you get useful information.
Also not all 'integration tests' are slow. If you can test using SQlite in memory, instead of pointing at a PG instance that needs to be provisioned, for instance, you can get a lot of your end-to-end testing running really quickly.
If you have good logging and debugging tools the failure can be quite quick to pin down. James Coplien suggests liberal use of assertions in code which is a really good idea and something C/C++ programmers used to do a lot of. Assertions can then be as effective as unit tests in terms of localising failure.
1. Do you have a a QA department doing manual or even automated testing? 2. Do you have performance testing? 3. Is the code base large or small? 4. Transactions versus analytics? 5. Social media? Some code doesn't need testing. Facebook doesn't test their code.
Each new project requires a flexibility to understand the reality of time and resources available for testing, the type of application and performance considerations. If one works at a bank or on transactional software then testing needs to verify exactness. If you are working on analytical software then what's another anomaly between friends, errors in your errors, who cares. If you are working on social media then just pump and dump like NodeJS.
That is the art of testing to me. A mind set of one size fits all with respect to the of value unit testing, integration testing, regression testing or manual testing is the opposite of art: it's ideology.
Integration tests are worthwhile even if you do have unit tests. They serve different purposes.
Ouch. It's 2017. I know it's a blog about unit testing, but using SHA-1, let alone unsalted SHA-1, for password hashing even if for illustration purposes is dangerous.
Rather than "arrange", "act", "assert", I've taken to writing the Gherkin spec inline with the test code, e.g.
@Test
public void onlyExistingEmailsCanResetTheirPasswords() {
//Given an email address which is not in the database
String email = "unknown@example.com";
when(userRepository.findByEmailAddress("unknown@example.com"))
.thenReturn(null);
//When a password reset is requested for that email
UserServiceImpl userService = ...
userService.startResetPasswordProcess("unknown@example.com");
//Then no password reset notification should be sent
verify(notificationService, never()).sendResetPasswordNotification(any());
//And the user should be given a success message so they can't determine if the email address is already present
verify(userInterface, once()).sendMessage("You have been sent Please check your email.");
}
This way you preserve the intent for the programmers that will come after you, but you don't need a complicated Gherkin runnerI find it very unusual to talk with developers who regularly modify their testing practice based on time and money.
The most expensive is to do it all: unit testing, integration testing, component testing, system testing, end-to-end testing, stochastic testing, performance testing.
The art of testing in no small part comes down to the art of money. How much bang-for-the buck does any testing provide given limited resources? I answer that question.
Take the workload difference between in house versus public usage.
If one releases software into the public domain then one has no reasonable expectation as to the kinds of data driving your code. For this kind of general purpose, heavily reused software then code coverage with, unit testing and mocking makes the most sense is my experience.
However, one can also write code for a very specific, limited usage. In those cases I find regression testing with regression data works best. They are not paying me to find bugs to satisfy code coverage.
I find understanding the workload is a significant factor in determining the kinds of testing I use.
It's sad that this is the state of the art when unit testing (but I have not found any viable alternative when the premise is that I have to use JUnit).