News for hackers. Stuff that matters.
Re:Questions to ask yourself when writing tests by discreteevent on Monday January 01, 2018 @08:04PM (#16049049)
"consider instead writing higher level tests that each each test more of the code."

I really like the way they keep repeating this as the answer to so many questions. To me it reads as a softly softly approach to weaning people off what appears to be a mania for micro level unit testing, driven by people like Uncle Bob.

Re:Questions to ask yourself when writing tests by Ace17 on Tuesday January 02, 2018 @01:20AM (#16050239)
> ... micro level unit testing, driven by people like Uncle Bob.

"The structure of your tests should not be a mirror of the structure of your code. The fact that you have a class named X should not automatically imply that you have a test class named XTest."

"The structure of the tests must not reflect the structure of the production code, because that much coupling makes the system fragile and obstructs refactoring. Rather, the structure of the tests must be independently designed so as to minimize the coupling to the production code."

http://blog.cleancoder.com/uncle-bob/2017/10/03/TestContrava...

Re:Questions to ask yourself when writing tests by ancarda on Tuesday January 02, 2018 @02:37AM (#16050489)
I really wish Uncle Bob would provide code examples with his blog posts and videos. I struggle to imagine what my tests would look like if I followed this. Possibly as my tests are so tightly coupled right now that refactoring is actually not possible in some cases.

Does anyone know of explations of this with a more hands-on approach, or is this simply a collection of ideas that can’t really be shown?

Re:Questions to ask yourself when writing tests by ed_blackburn on Tuesday January 02, 2018 @07:10AM (#16051418)
Practical advice? Consider making every type internal. Then open them up to what is strictly required to be public.

Now you are testing the behaviour of your application through its public surface. This reduces the brittleness of your tests because you can change the internal implementation without rewriting your tests. You have higher assurance. It'll also force your hand to enforce invariants and place guard clauses in the right places rather than "everywhere".

If you follow Cockburn's Ports and Adapters approach too, then you can substitute adapters like persistent state, buses, HTTP clients for appropriate in-memory equivalents.

Re:Questions to ask yourself when writing tests by hdi on Tuesday January 02, 2018 @05:10AM (#16051003)
I've been wondering about that for a while.

So far, I've not been able to find any examples of test architecture that follows those principles online or in my day job.

I've also been too lazy to do a side project and explore a more decoupled and scalable test suite. Maybe I should get off my arse and finally do it.

Re:Questions to ask yourself when writing tests by twic on Wednesday January 03, 2018 @02:26PM (#16064193)
If you're writing a web application, i've had a reasonably happy time with tests at the controller level, or perhaps right below. You want an interface where values go in and out that correspond to fairly user-level ideas, but which are still tractable for testing.
Re:Questions to ask yourself when writing tests by spion on Tuesday January 02, 2018 @08:37AM (#16051742)
I think my example captures the spirit of this: https://news.ycombinator.com/item?id=16049441
Re:Questions to ask yourself when writing tests by vog on Tuesday January 02, 2018 @10:18AM (#16052281)
I agree that these types of tests are very good and usefuly, but:

Don't they use the wrong term for them?

I believe these tests are more commonly called "integration tests", not "unit tests".

Or, did I misunderstand something?

Re:Questions to ask yourself when writing tests by wst_ on Tuesday January 02, 2018 @11:20PM (#16058351)
Integration tests are testing multiple modules and the way how they cooperate. These are mora a feature tests. Take a module as your unit, mock externals, give it an input and check the output/outcome.
Re:Questions to ask yourself when writing tests by crdoconnor on Tuesday January 02, 2018 @08:01AM (#16051589)
>Then, clearly, if a small change to the production code causes large changes to the tests, there is a design problem. > >Therefore the tests must have their own design. They cannot simply follow along with the structure of the production code.

The jump indicated by the "therefore" confuses me. I essentially couple my test to production behavior, insofar as it is possible. I do this to test program behavior realistically and because I believe tests should, in some sense, form a specification for the program they test. I don't really care about "testing code"; I care about testing behavior.

I don't have the problem of small changes to code necessitating large changes to tests. It makes me wonder what he does that is causing that.

Re:Questions to ask yourself when writing tests by seanwilson on Tuesday January 02, 2018 @12:02AM (#16049984)
The argument I get against this is that when a higher level test fails, it's harder to locate the lines of code that broke the test unlike when you have lots of unit tests. I don't find this convincing though. Most of the time it's going to be pretty obvious looking at what lines of code have changed since the last working commit. Lots of projects get by without any tests at all as well. I'm not saying to skip testing completely but it comes as a cost and you need to be practical at weighing up how much time to put into it vs how much time you're going to save. Writing unit tests for everything takes time.
Re:Questions to ask yourself when writing tests by blowski on Tuesday January 02, 2018 @03:19AM (#16050631)
There is no silver bullet. Personally, I let a combination of complexity and importance guide my tests.

The more likely it is that a piece of code will break, and the more business damage it will do if it does break, the more tests I wrap around it.

For self-contained algorithms that have a lot of branches or complex cases, I use more unit tests. When the complexity is in the interaction with other code, I write more high-level tests. When the system is simple but critical, I write more smoke tests.

If I’ve got simple code that’s unlikely to break and it doesn’t matter if it does break, I might have no tests at all.

Re:Questions to ask yourself when writing tests by ed_blackburn on Tuesday January 02, 2018 @07:12AM (#16051423)
100% In critical areas I would suggest parameterised tests are worth the effort, especially in conjunction with generators. Property-based testing in FP for example, or just test data generators that'll generate a good range.
Re:Questions to ask yourself when writing tests by blowski on Tuesday January 02, 2018 @08:58AM (#16051832)
I'm not sure what's involved there. Do you have more detail, like a good blog post, to read about how to do that?
Re:Questions to ask yourself when writing tests by dvlsg on Tuesday January 02, 2018 @11:41AM (#16053012)
Not OP, but I particularly enjoy the fsharpforfunandprofit article about it.

https://fsharpforfunandprofit.com/posts/property-based-testi...

Re:Questions to ask yourself when writing tests by crdoconnor on Tuesday January 02, 2018 @08:13AM (#16051641)
>The argument I get against this is that when a higher level test fails, it's harder to locate the lines of code that broke the test unlike when you have lots of unit tests. I don't find this convincing though.

This is a valid observation but the problem clears up when you start integrating better debugging tools into your testing infrastructure: having the ability to intercept and inspect API calls made by your app, launch a debugger in in the middle of the test, etc.

It is also minimized by writing the test at the same time (or just before) the code that makes it pass.

Re:Questions to ask yourself when writing tests by ajmurmann on Monday January 01, 2018 @08:21PM (#16049121)
I'm not sure I agree with the "instead" in his recommendation. "micro level unit testing" comes with its own benefits, like faster feedback and also design feedback that integration or acceptance style tests won't give you. I like to start out with a high level acceptance tests and then write unit tests for every change to involved classes. You really need a healthy testing pyramid.
Re:Questions to ask yourself when writing tests by discreteevent on Monday January 01, 2018 @08:38PM (#16049204)
The problem is that, in my observation over a number of codebases with many developers: A lot of unit tests end up testing the implementation. When you go to refactor, these tests break which slows you down. To me it seems nearly impossible not to end up with these kinds of net negative tests when you follow a micro approach. I mean the approach outlined in books and blogs where you write a test and then write only a few lines of code. It's all very neat and satisfying but for me it's just a form of fooling myself. I can see this if I honestly measure the net effect of the these kinds of tests in the large. The only thing is that they might sometimes help me locate a problem a few seconds faster, but that's all.
Re:Questions to ask yourself when writing tests by cle on Monday January 01, 2018 @10:17PM (#16049596)
Agree. I am so sick of having to code in extremely brittle codebases that are impossible to refactor because of the sheer volume of UTs that are tightly coupled to very specific implementation details--added to satisfy a minimum code coverage metric. UTs were supposed to save us from the pain of refactoring, but in many cases they just trade one time-sink for another, and the cost equation remains the same (not to refactor, because it's too time consuming).

In this same vein, I propose another question:

   How similar does the test look to the production code?
These kinds of super-granular, brittle tests have a way of looking very similar to the code they are testing (e.g. super strict mocking of every dependency almost looks exactly the same as the code under test!). That style of testing is basically writing the code twice, and verifying that the second copy does indeed equal the first. I'd rather just write the damn code twice, and save myself from having to figure out all the minute differences between testing libraries that framework jockies bikeshed over.
Re:Questions to ask yourself when writing tests by u801e on Monday January 01, 2018 @10:27PM (#16049644)
> I am so sick of having to code in extremely brittle codebases that are impossible to refactor because of the sheer volume of UTs that are tightly coupled to very specific implementation details

I think this comes from "unit tests" where they have assertions such as

  assertThisOtherSpecificMethodNameWasCalledWithTheseSpecificallyNamedParameters
If more methods were written to not call out to disk or some external service (e.g., a database or API) and we had a main method that handled the external communication, then the unit tests would be much less fragile. This would also eliminate the need for mocking since the methods that are tested have no side effects.

For testing dependencies, an environment where a test instance of the database, API, or other external service is needed. Then the code could be tested against an actual implementation rather than a mock of it.

Re:Questions to ask yourself when writing tests by yeukhon on Tuesday January 02, 2018 @12:46AM (#16050130)
> If more methods were written to not call out to disk or some external service (e.g., a database or API) and we had a main method that handled the external communication, then the unit tests would be much less fragile.

I am not really following. You can write a seperate function that handles database query, then call this function in your code under test, or one of your argument in the code under test is the databse object handler (this allows you to abstract from a specific db handler). But if you don’t mock out the handler with a “dummy handler”, you will be making real databse call. That is not UT.

You will be doing functional testing.

So you can only abstract so much to get your code testable.

Re:Questions to ask yourself when writing tests by u801e on Tuesday January 02, 2018 @10:06AM (#16052204)
> You can write a seperate function that handles database query, then call this function in your code under test

You can, but that still requires that you mock that call in order to test the method that calls your database query method. But, if you make it such that your method takes the result of the database query as a parameter, then you can test your method without having to use a mock. In other words, you can change this (which requires mocking get_db_result to test):

  def a_method_to_test(param1, param2):
      db_result = get_db_result(param1)
      # do something with db_result
to this:

  def a_method_to_test(param1, param2, db_result)
      # do something with db_result
Now you can test a_method_to_test without having to mock out the call to get_db_result by just passing in whatever you want as the db_result parameter.

Basically, doing this will separate code that manipulates data from code that either writes or reads data. You can unit test methods that manipulate data, but you will need to do functional/integration testing of code that writes or reads data from other sources.

Re:Questions to ask yourself when writing tests by lmm on Tuesday January 02, 2018 @03:23AM (#16050647)
Rather than having 3 different business logic methods that call out to the database, you have each construct a command object and then have a separate service that calls out to the database based on these commands. You can then test the 3 business logic methods by testing that they construct the correct commands based on their parameters.
Re:Questions to ask yourself when writing tests by falsedan on Tuesday January 02, 2018 @05:33AM (#16051082)
Yeah, exactly. To put it another way: get your business logic components to return data structures (a list of DB actions or an updated dict), and your core controller to turn those data structures into DB calls. Then your tests simply say: here’s a certain environment, what action do you think should be performed?

If you think this sounds like mocking, you’re right (it is like mocking, it isn’t mocking). It has the bonus of making it easier to inspect the logic & expose it to the user ("hey I’m about to do these things, does that sound ok to you?").

Re:Questions to ask yourself when writing tests by yeukhon on Tuesday January 02, 2018 @08:07AM (#16051614)
Thank you. Would you mind to elaborate a little more with perhaps a little pseudo-code snippet?
Re:Questions to ask yourself when writing tests by lmm on Wednesday January 03, 2018 @11:18AM (#16062226)
https://michaelxavier.net/posts/2014-04-27-Cool-Idea-Free-Mo... is a nice simple example if you don't mind reading Haskell. (Redis rather than a database, but the technique is the same)
Re:Questions to ask yourself when writing tests by discreteevent on Tuesday January 02, 2018 @05:55AM (#16051163)
Then maybe just consider doing functional testing. Assertion code in a mock is, by definition, code that tests an implementation. In the example given, suppose you wanted to replace the database with a nosql version. Now you have to throw away or modify your tests even though the behaviour of your system has not changed
Re:Questions to ask yourself when writing tests by yeukhon on Tuesday January 02, 2018 @08:03AM (#16051602)
> In the example given, suppose you wanted to replace the database with a nosql version. Now you have to throw away or modify your tests even though the behaviour of your system has not changed

Well, not really. Because now I have the DB stuff all contained in a separate function (or handler which can be proxy to the correct DB engine/type of DB), so if with careful design I should be okay.

    def create_account(user_manager, user_details):
       user_manager.create_account(user_details)
Here user_manager can abstracts away the exact DB type/engine like Django.

Of course this is ideal, but that was the motive. I do agree on mocking == testing implementation in general, and functional testing is almost always the way to go... since mocking returns dummy data / fixture, might as well return from a real database. The downside is speed :/ (there are various of tricks like setUpClass, run every test or group of tests in docker containers in parallel, but takes much longer than UTs). Ugh trade-offs.

Re:Questions to ask yourself when writing tests by darioush on Monday January 01, 2018 @11:20PM (#16049846)
Another way they prevent refactoring is by creating the work for you to implement the same type / number of tests on your new code so your code review doesn't look like it's deleting 100 tests.
Re:Questions to ask yourself when writing tests by ajmurmann on Monday January 01, 2018 @11:28PM (#16049873)
I've seen this with out differently on different code bases. Particularly on Rails code bases I've seen some of the symptoms you describe. On more recent Java projects I've seen the opposite where code that needed to change actually just ended up getting swapped out. The "only one reason to change"/open-closed dream come true. Old classes and unit tests just got thrown out. On those acceptance tests were the pain point when behavior was changed on purpose.

I'm still not sure how to get the good outcome every time. Maybe it's just well designed interfaces ‍️

Re:Questions to ask yourself when writing tests by rimliu on Tuesday January 02, 2018 @02:41AM (#16050499)
I recommend https://www.sandimetz.com/99bottles/ to everyone. Also her other book, Practical Object Oriented Design in Ruby. They both communicate the essential points very clearly. Also, after reading those books I got a better idea why OOP has a bad reputation, and why people are so bad at writing tests. Somehow these skills are presumed to be easy and already there when in reality they need practice, a lot of it.
Re:Questions to ask yourself when writing tests by querulous on Monday January 01, 2018 @11:21PM (#16049848)
what's wrong with just deleting these now-irrelevant tests?
Re:Questions to ask yourself when writing tests by discreteevent on Tuesday January 02, 2018 @05:49AM (#16051143)
You can delete them but the fact that they are irrelevant now even though you didn't change the behaviour of the software means that it was a waste of time writing them in the first place.

Secondly it decreases your confidence in the refactor. In a classic refactor, nothing should break. This is because a good set of tests are a way of documenting and verifying the design/behaviour of the system.

Finally, often in a codebase with micro tests, there will be an expectation that you replace one set of micro tests with another.

Re:Questions to ask yourself when writing tests by fnord123 on Tuesday January 02, 2018 @05:27AM (#16051059)
Nothing. Integration tests are your hypothesis/experiment. Unit tests are your lab setup.
Re:Questions to ask yourself when writing tests by crdoconnor on Monday January 01, 2018 @08:54PM (#16049266)
>design feedback that integration or acceptance style tests won't give you.

That "feedback" is the pain you feel when you have to maintain one form of tight coupling (ordinary bad code) combined with another (micro-level unit tests).

Higher level tests won't cause you that 'guiding pain' because they aren't as tightly coupled to your implementation.

IMO you don't need to write tens of thousands of lines of unit test code to spot that you're building tight coupling in. It's something you can spot simply by knowing what to look for.

Moreover, if you make a design mistake or introduce tech debt lower down the stack, having a panoply of low level unit tests means that refactoring will break those tests even if you haven't introduced any bugs. IME that causes a dangerous cementing effect on bad code.

I think if you've got a module which is self contained, reusable and tightly scoped, it's worth surrounding with a lower level test. But, if you don't, you're doing more harm than good by surrounding a module with tests.

Re:Questions to ask yourself when writing tests by twic on Wednesday January 03, 2018 @02:34PM (#16064259)
> You really need a healthy testing pyramid.

I don't think you do. I think a testing pyramid is a sign of an unhealthy approach and an unhealthy codebase.

I think what you need is a testhenge. For those who aren't familiar with henges, here's a typical (although poorly maintained) one:

http://www.english-heritage.org.uk/remote/www.english-herita...

Rather than being massive at the bottom and then getting thinner as it goes up, there is a continuous band around the top, covering everything, supported by uprights that dive deeper down, just where needed.

That is, you need a layer of high-level tests for everything (for a web application, some mix of browser tests or controller-level integration tests), along with component-level integration tests and isolated unit tests for the bits of the system that are particularly risky (complex, error-prone, critical, new, old, etc).

Re:Questions to ask yourself when writing tests by Vinnl on Tuesday January 02, 2018 @04:20AM (#16050849)
On the one hand this is true, but as someone who does prefer keeping unit tests relatively small in order to be able to pinpoint issues easier and not have tests break as often without it being clear why, I think the article does strike a nice balance of only recommending it where it really makes sense, rather than simply stimulating you to write as high-level tests as possible.
Re:Questions to ask yourself when writing tests by newfoundglory on Monday January 01, 2018 @11:32PM (#16049888)
I don't like it, it reminds me of the time a colleague wrote 2 separate pieces of new functionality and wrote one single end to end test that used both of them, as the "most efficient" way to test it.
Re:Questions to ask yourself when writing tests by philipodonnell on Tuesday January 02, 2018 @12:36AM (#16050099)
Honest question: can you expand on why this is bad? Doesn't efficiency outweigh respecting feature boundaries in tests?
Re:Questions to ask yourself when writing tests by Ace17 on Tuesday January 02, 2018 @01:48AM (#16050350)
> can you expand on why this is bad?

Because most of the time, it reduces "test precision". Which means when such a test detects an issue, there's now a bigger area of the code where the issue could be located.

> Doesn't efficiency outweigh respecting feature boundaries in tests?

In the end, what we're trying to minimize here is feature development time.

This of course depends on the feedback loop duration (build + run tests), which is why test efficiency is important ; but there are other factors.

Feature development depends on the time it takes to locate the error when a test fails ; a test signalling that "something is wrong somewhere" is not very usefull (in some cases, it can be, if it runs extremly fast - because you can generally see the error with "git diff").

However, infinitely precise tests are often undesirable, because they tend to have extremely rigid expectations about the behavior/API of the code under test, discouraging refactoring, and thus slowing down the development process.

Let's keep in mind that "testing = freezing". More precisely, you're freezing what your tests depend upon (by adding friction to future modifications). So be careful what you freeze: the initial intent of testing is to increase code flexibility. If you can't modify anything without breaking a test, you're probably missing their benefit.

Re:Questions to ask yourself when writing tests by arkh on Tuesday January 02, 2018 @04:01AM (#16050782)
> Because most of the time, it reduces "test precision". Which means when such a test detects an issue, there's now a bigger area of the code where the issue could be located.

Tests are not a debug tool. Tests are here to tell you when you broke something.

When this happen you can get your debugging toolbox out: stack traces, profilers and things like GDB. And then follow the steps your test script did.

Re:Questions to ask yourself when writing tests by amarkov on Tuesday January 02, 2018 @06:35AM (#16051294)
All the projects I've most enjoyed working on had clear, explicit test failures, which almost always gave me enough information to hunt down what I'd broken and where. Obviously that's not realistic for some kinds of projects. But even in a legacy C project, if I had to pull out stack traces and profilers and GDB every single time I wanted to understand why a test failed, I would say I'm working in a pretty terrible codebase.
Re:Questions to ask yourself when writing tests by newfoundglory on Tuesday January 02, 2018 @04:28PM (#16055874)
I disagree and am horrified by the dystopic image of our entire test suite having two possible results: "everything passed" or "something is wrong".
Re:Questions to ask yourself when writing tests by arkh on Tuesday January 02, 2018 @06:03PM (#16056716)
Not two results.

But "when you click on this after that this happen while it shouldn't" is usually enough info to start debugging: you have reproducible steps. Which you can do with a debugger running so you see exactly were and how things break.

And it is a lot less brittle than "well we tried to refactor some minor thing and now everything is red; but we don't know if the software behavior changed or just because our tests were just checking the implementation".

Re:Questions to ask yourself when writing tests by newfoundglory on Wednesday January 03, 2018 @03:52AM (#16059500)
well, if you're determined to write stupid tests you can do it at any level. And that is not enough info to start debugging unless you had the machine in a known and reproducible state to begin with, which is where we get back to writing focused reproducible tests.