r/coding • • Oct 29 '17

Mocking is a Code Smell

https://medium.com/javascript-scene/mocking-is-a-code-smell-944a70c90a6a
69 Upvotes

69 comments sorted by

62

u/KabouterPlop Oct 29 '17

On the other end of the spectrum, it’s common to see developers get so sucked into the dogma of TDD that they think they absolutely must achieve 100% code coverage, by any means necessary, even if that means they have to make their codebase more complex to pull it off.

People keep saying this, but I've yet to meet such a developer.

19

u/handshape Oct 29 '17

I've seen it in the wild in a developer who was promoted to managing a dev team. He treated code metrics like a score in a video game. He also delighted in crapping on new hires during their code reviews.

A delightful human being, I assure you.

6

u/[deleted] Oct 29 '17

This sounds like my old lead dev. He was nice most of the time but the guy had no pragmatism and would seriously hold back delivery going down very precise but arbitrary rabbit holes with regards to how certain stuff should be implemented.

On my new team it's definitely an example of what OP talks about. There's literally hard coded if/else statements in production code to hit coverage, like if parameter = x then do this else do real world scenario...

3

u/Developer_dave Oct 29 '17

Honestly, many of us get promoted before we are ready to lead and just don't know how to handle it. I hope this individual is just a bit out of his depth and compensating in all of the wrong ways.

I've been a crappy lead and I'm not proud of it. These days I'm more of an individual contributor type who takes point on things. I'm past all of the posturing required by my current employer to attain a leadership position.

8

u/myplacedk Oct 29 '17

People keep saying this, but I've yet to meet such a developer.

I've seen a test method just for checking that a certain constructor is private.

But I agree, I haven't seen any sign that it's common.

8

u/BobSacamano47 Oct 29 '17

I worked with a guy who made a class with 10 nullable properties. He wrote 10 unit tests, one to make sure each property was, in fact, nullable.

1

u/BobHogan Oct 29 '17

That might not be entirely his fault, but it might have been ingrained in him. I know that I've had a pretty poor professor who would force us to write tests like that, for everything single property in every class. No purpose to those tests at all, but it was required in every assignment

1

u/hvidgaard Oct 30 '17

In fairness, if the correctness of the program relies on those properties being nullable, they are perfectly good unittests to write.

1

u/voronaam Oct 29 '17

I've seen two separate projects that had test for the logging library. "test that debug logs on DEBUG", "test that trace does not log when not enabled", etc.

1

u/myplacedk Oct 29 '17

I've seen two separate projects that had test for the logging library. "test that debug logs on DEBUG", "test that trace does not log when not enabled", etc.

Yeah, testing included code, I've seen that too.

  1. Add jar (actually maven dependency)

  2. Copy tests from that project

4

u/Enumeration Oct 29 '17

I worked with people at my last job who did this all the time.

There is definitely a law of diminishing returns when it comes to code coverage.

1

u/[deleted] Oct 29 '17

There is definitely a law of diminishing returns when it comes to code coverage.

I did it once. The trade-off is inevitable and costly.

4

u/[deleted] Oct 29 '17

People keep saying this, but I've yet to meet such a developer

I worked at a company where 100% code coverage was mandatory. It was insane how deep we went to accomplish that.

Then, at the same time, we'd rely on 3rd party packages with no clue how covered they were. But 100% coverage, have to have that 100% coverage no matter how valuable it is.

3

u/Woolbrick Oct 29 '17

It's been the official policy at my company for about 4 years now.

Everyone just ignores it though. Managers only freak if the code coverage numbers go down. If they stay flat, it's cool. Hovering around 30% now.

3

u/[deleted] Oct 29 '17

100% code coverage

I achieved that once. I regret every minute of it.

2

u/andrew_rdt Oct 29 '17

If I had to pick something arbitrary I use 90%. The functions that actually need full coverage are larger so getting those gets you way past 50 sometimes. Of course there are always exceptions and some app layers don't need any testing. So with that 90% rule the project total could be much less.

1

u/Na__th__an Oct 29 '17

My team unit tests our Spring configurations in the name of 100% code coverage. We multiple unit test suits with over 1k LOC. Some classes have 3 separate unit test suites to achieve full coverage. They definitely exist.

0

u/[deleted] Oct 29 '17

[deleted]

4

u/way2lazy2care Oct 29 '17

I 100% agree with you, but I think the author agrees with you also. His point isn't that DI is bad. His point is that DI isn't a silver bullet you should be using for all your unit tests. DI and excessive mocking can be symptoms that your classes are too tightly coupled, and it's probably better to decouple the classes than it is to require extra mock objects in order to get extra test coverage.

I had a similar knee jerk reaction at first, but the authors point seems to be more in line with, "if your unit tests are too complicated, maybe your code is crappy," rather than, "don't worry about test coverage."

0

u/[deleted] Oct 29 '17

[deleted]

2

u/way2lazy2care Oct 29 '17

It's not that far out of line with his article. It's a little bit click baity, but if you wrote an article that said, "Too Many Parameters is a Code Smell," it would be pretty accurate despite functions with too many parameters being ok in lots of cases. After all he did say it was just a code smell and not that it was bad design/implementation outright.

1

u/Jestar342 Oct 30 '17

Just to point out: that title would mean nobody would read the article. It'd provoke the "well no shit" reaction and get passed over. At least with this title it's being discussed.

3

u/pudds Oct 29 '17

Dependency injection? Sure, its value outside of tests is contentious.

It's actually contentious? In code that needs to support multiple behaviours, it's pretty invaluable IME.

0

u/Jestar342 Oct 29 '17 edited Oct 30 '17

the added testability is a goddamn side benefit

No it isn't. This the entire point of TDD. I mean the test driven bit of TDD. The tests are driving you to write your software in such a way that benefits the overall design of your system. That's a goal, not a side benefit.

e: Thanks for the downvote with no discussion! You make reddit the great place it is. thumbs up

2

u/[deleted] Oct 30 '17

[removed] — view removed comment

1

u/Jestar342 Oct 30 '17

I did keep reading and it still stands that that is the very purpose of TDD. Not "having tests" but TDD.

0

u/[deleted] Oct 29 '17

[deleted]

5

u/shadowdude777 Oct 29 '17

Yeah, frameworks really help and simplify the issue, but it's usually enough to pass in all classes used in a class in its constructor. I'm working with some really shitty code right now in an SDK that just grabs shit it needs from the Android framework right in the body of a 300-line method, many layers deep into a bunch of conditional statements. How can I possibly test or verify this?

2

u/[deleted] Oct 29 '17

it's usually enough to pass in all classes used in a class in its constructor

Yeah, a lot of quality code does exactly this, but people don't typically call it "dependency injection" unless there is a framework involved. For example, I see this pattern all the time in Python code, but I've never once heard the term "dependency injection" in relation to a Python project.

1

u/shadowdude777 Oct 29 '17

DI frameworks generally do a lot more than this, though. Constructor-provided dependencies are important for sure. But DI frameworks generally also provide you with a way to manage what dependencies are available in what scopes. The good ones, like Dagger 2, even make it compile-safe, so you can know that if your program compiles, all dependencies are being properly provided to your dependent classes.

1

u/spoonraker Oct 30 '17

The pattern is called Inversion of Control. It's one of the SOLID principles. Dependency Injection typically relies on this patten being implemented, but implementing it doesn't necessitate the use of Dependency Injection.

2

u/[deleted] Oct 30 '17

Oh, that clears it up.

1

u/mtnbarbours Oct 30 '17

Not quite.

I = Interface Segregation

You're probably thinking of dependency inversion, which is similar to IoC...

https://stackoverflow.com/questions/3912504/difference-between-inversion-of-control-dependency-inversion-and-decouplin

I still refuse to acknowledge Liskov. :-)

1

u/spoonraker Oct 30 '17

I never said it was the "I". Yes I was referring to dependency inversion, which is close enough to the same thing for the context of this conversation. They're referring to the same coding patten if you remove the context of the rest of the application.

2

u/[deleted] Oct 29 '17

[removed] — view removed comment

20

u/welpfuckit Oct 29 '17

I feel like whether to write a unit or integration test and the extent of effort is a judgment call and anyone strictly following any sort of dogma is liable to completely miss the point. Are you writing an open source library, backend API, or frontend? If my application uses an ORM and I am using it in a standard way, do you expect me to not mock it given the performance penalty from the database interaction and that there are tests for the ORM upstream? Conversely, if I have a complex algorithm that provides a set of geospatial results after interacting with a database, do you think I shouldn't hit the database in a test to guarantee that the same results are being returned in the case the algorithm is tweaked/optimized?

We get paid to be developers, apart from being specialized labor, to utilize our brain and make sensible choices given the requirements/context.

7

u/andrew_rdt Oct 29 '17

The whole article seemed to just defer some unit tests to integration tests. For a correctly tested app you need some combination of both and the amount of work is roughly the same it just depends where you want to spend effort.

9

u/doomvox Oct 29 '17 edited Oct 29 '17

My attitude toward tests:

  • Database mocking has always been a very weak idea: databases, if you use them correctly are not just neutral data stores, they've got data types and uniqueness constraints if not triggers and stored procedures.

  • If distinguishing between "unit tests" and "integration tests" means punting on checking your code againt an actual database, you should drop that distinction. If the database munges my data in a way I don't expect, I really need to know that sooner than later. Another way of putting this is "integration" tests are more important than "unit" tests: maybe you should write them first and run them more often.

  • You can't take test code too seriously, it should be regarded as secondary to the main code. It's okay to be a little sloppy with it. When a test breaks because the test was fragile, you should certainly think about how to make it more robust, but it's not a crime against humanity to just delete the test. Getting hyped up about things like "no external dependencies in unit tests!" is counter-productive.

5

u/doomvox Oct 29 '17

A few other thoughts: ideally test code should run against a local copy of a database, with identical schema to the live one, but a stripped-down data set in a known state at the start of the test run. In the absence of a test database, you can often write reasonably robust tests simply by using old data that has had time to settle down. E.g. three-year old financial data isn't likely to change much.

3

u/[deleted] Oct 30 '17

[removed] — view removed comment

4

u/Jannis_Black Oct 30 '17

Creating the state that they need is essentially the same thing, since it means when the actual test runs the database is in a known state.

0

u/[deleted] Oct 31 '17

[deleted]

1

u/Jannis_Black Oct 31 '17

That depends on your application

3

u/Jestar342 Oct 30 '17

They are called "unit" (note the singular form) because they are testing a single unit of behaviour. This name is supposed to imply that this test cannot be broken down further, even if you wanted to try. Ergo the moment you have more than one single unit of behaviour, it's no longer a unit test.

Assuming one is a stickler for names, that is.

2

u/kagevf Oct 29 '17

Getting hyped up about things like "no external dependencies in unit tests!" is counter-productive.

I think the distinction is useful because of how accessing external resources can slow down test execution speed. For example, run unit tests with no (or least minimal) external dependencies on every commit (CI build), but run integration tests and end-to-end tests as part of a nightly build.

I agree, though, that getting dogmatic or hyped about it isn't useful, and it's up to each team to figure out what approach works best in their environment, as far as what should be targeted for tests, isolation strategy, etc.

2

u/[deleted] Oct 30 '17

[removed] — view removed comment

2

u/kagevf Oct 30 '17

Yeah, that's 1 thing we've noticed ... our unit tests taking however many ms and our miserable integration tests taking ... oh! they're actually not that slow! :)

It might be better to classify tests as "fast" vs "slow" instead of "unit" vs "integration" or maybe assume all unit tests are fast and specify which integration tests are fast and slow ...

1

u/nerdshark Oct 30 '17 edited Oct 30 '17

If the database munges my data in a way I don't expect, I really need to know that sooner than later.

Sure, and that's one of the things integrations tests are for: testing the assumptions and behavior in your project system wide. I think just "integration" is too vague a word for this kind of test; it really ought to be called something like "systems integration test". The benefit of distinguishing between unit testing and systems integration testing is that it lets you test things at different levels of granularity or abstraction. The distinction gives you a starting point for determining what a given test should focus on, the appropriate testing procedure, and how test dependencies need to be handled.

3

u/Agrees_withyou Oct 29 '17

I see where you're coming from.

24

u/i9srpeg Oct 29 '17

If you read medium long enough, literally anything becomes a code smell. I have to start ignoring people who talk about code smells. Programming can be such a cult.

22

u/praetor- Oct 29 '17

"_____ is a code smell" is such a clickbaity title, and calling something a "code smell" is dismissive and typically comes from someone with a narrow perspective (such as the author of this article only talking about JavaScript).

What articles like this fail to address is that there are a wide variety of scenarios under which software is built, from a startup in an early iteration to a megacorp maintaining a 20 year old integration library.

Trying to crap on a technique because it doesn't apply to your particular scenario shows a lot of immaturity imo.

3

u/[deleted] Oct 30 '17

[removed] — view removed comment

2

u/praetor- Oct 30 '17

I usually just describe what I'm seeing and talk through it, probably by asking questions and listening to rationale.

I feel like telling someone their stuff has a "code smell" is pretty rude as it implies an unpleasant "smell" e.g. shit. I know I wouldn't appreciate it, and I'm in a senior role and don't believe in tearing people down for mistakes so I wouldn't say it to others.

4

u/doomvox Oct 29 '17

Fortunately they stick a javascript popup in my face to remind me that I've been reading the site too much. I generally take the hint and just go away.

3

u/jaybazuzi Oct 30 '17

Mocking is one of the most severe code smells - it lets you test where there is tight coupling / pretend that the coupling isn't there.

The win from TDD comes from detecting and addressing design issues in code, so when mocks hide your coupling, you throw away the value of TDD.

Arlo Belshee used to do legacy code saves, and found that if the system had mocks, it took twice as long to recover the code. That led him to saying "Mocks are Evil".

2

u/Vorlath Oct 30 '17

Sounds like the author and every commenter here has never worked on a large project.

1

u/yarauuta Oct 30 '17

Alot of people in this thread forget that the main purpose of testing is to freeze code/modules contracts/api's to make it possible to change the code later.

1

u/thephotoman Oct 30 '17
  1. I tend to regard coverage as a metric not of quality, but of how well your team is doing at following the TDD process if that's what you're doing. If you aren't doing TDD, well, 100% coverage isn't useful.

  2. Integration tests matter. They're just as much a part of your testing procedures as the unit tests. If you've got to interface with a database, you need to ensure that your integration tests handle those failure conditions.

1

u/adymitruk Oct 30 '17

All the points the article makes are best served by using CQRS/ES.

1

u/ferociousdonkey Feb 18 '22 edited Feb 18 '22

The point is to leave jargon and ask yourself these questions:

  1. what exactly am I testing here?

  2. what's the simplest way to test this?

Mocks, stubs, etc. they should be used accordingly. In the end you need a mix of integration, functional and unit tests.

People who just follow dogmas are simply not good programmers.

13

u/[deleted] Oct 29 '17 edited Oct 29 '17

[removed] — view removed comment

4

u/u801e Oct 29 '17

There's the problem. If you define "unit test" as "no external dependencies" then unit tests are woefully inappropriate for many types of code.

If you write your code where mix IO with logic, then of course unit tests that expect to test methods that have no external dependencies won't work. But does mocking out dbContext get you anything in terms of verifying that the method works as expected? I would say it doesn't because you're just testing your mock.

Now, if you were to do further processing of the value of result, then you could make a method that takes result as a parameter and returns the desired value after processing result. That method wouldn't have any side effects and would be unit testable without having to set up any mocks. The code that queries the DB would be handled in an integration test against a test instance of the DB filled in with pre-determined values.

2

u/daedalus_structure Oct 30 '17

Sure. But what does that actually prove? That your compiler works?

Yep, and that your mock works.

But it's not only a case of no value added, it's even dangerous due to all the situations where you still get a green test but the code is actually broken.

Even ignoring the obvious issue with database constraints that won't be included in the mock the attempt will unwittingly change the LINQ provider. It's not so hard to get into a situation where you write code that works with LINQ to Objects but can't be translated into a valid SQL statement, and the test won't be the wiser.

2

u/creativeMan Oct 30 '17

To be honest, dbContext mocking seems to be more a .NET thing. You don't have this problem in Django, for instance, because Django's default test framework creates an in memory clone of the database when you run tests.

I recently worked on a .NET MVC project and found myself writing a lot of test code and architectural code just to make sure tests can be run without dbContext. From what I've seen, the common practice is that you write separate Repository classes, Unit of Work classes and Service classes, often for each Model so that you can mock properly and have decoupling. However, DbContext is described officially as a repository and unit of work class. So it makes it seems like a total waste of time.

1

u/JavadocMD Oct 30 '17

I think the author addressed this: 1) you've used imperative composition, and 2) this (I/O) is an integration point not worthy of a unit test if you instead employ declarative composition.