views:

51

answers:

4

Hi,

What unit tests generally tend to be hard to write and why? I am particularly interested in methods which don't need mocking.

Thanks

+1  A: 

Two cases where unit testing is made difficult:

Methods that invoke static methods that belong to other classes, particularly when those other classes have static state, or do significant work. Being stuck trying to "unit" test a method that, through transitive closure, does database queries can suck.

Methods that create instances of other classes directly (i.e., via new), particularly when the constructor of the other class does itself requires static state, or when it does significant work in the constructor.

Dave W. Smith
I've done unit testing with static variables/methods. Bad things can happen.
Chance
A: 

A great A to Z guide of testability concerns with side by side code examples of easy/hard to test code can be found in Misko's extensive testability guide.

Click on the "flaw #x" links (they look like plain text but they're separate links).

Mark Simpson
A: 

Big, complex methods that do lots of things at the same time that really should've been separated. (example: get something from a configuration object, create a URL based on some variables, encode the URL, send a request, do something with the response... you get the drill).

Everything static. Things created with New, although I haven't found a proper way to avoid it without spamming the entire application with factories.

Cthulhu
consider using dependency injection and you won't have to litter the application with factories. would agree it's hard to without a DI framework.
Rob
A: 

It's almost always about dependencies.

Most code depends on external systems such as databases, file systems, email clients, networks, etc. It's also common to have dependencies on major internal systems (e.g, the spell checking module, or the recalc engine...).

If these dependences are not easily substitutable, then the system becomes hard to test. Classes that call statics and singletons are the worst offenders, but any class that doesn't accept it's dependencies via constructor or properties will be hard to test.

There are some legitimate situations that are hard to test:

  1. Concurrency
  2. User Interface - this is why the trend is towards MVC architectures that create ViewModels which can be easily tested. The actual rendering is minimized - this is called the humble dialog or humble object pattern in the test literature.
Rob