1

I'm looking for an example to illustrate difficulties when testing a static class vs. instance class. Can someone provide one?

notlkk
  • 1,231
  • 2
  • 23
  • 40
  • Well, how do you test a class for time differences if it uses `DateTime.Now`? – Oded Jun 27 '12 at 18:42
  • You might want to check [this answer](http://stackoverflow.com/a/10633109/343266). – k.m Jun 27 '12 at 18:47
  • Search SO [top-right] with "static [unit-testing]". You'll find a lot of posted difficulties. Static classes with pure functions are not difficult to test - e.g. the methods of the Math class. Read also: http://stackoverflow.com/a/4222788/1695 – Gishu Jun 29 '12 at 06:48

1 Answers1

0

A class that makes use of other types is said to have a dependencies on those other types. When you unit test a method in a class, you generally try to test what the method is doing, not what the dependencies are doing. A common way to set up your objects to support these scenarios is to use dependency injection. Dependency injection is a common pattern that improves testability. Static classes don't work well with that pattern, making unit testing of classes that use static classes difficult.

For example, if you have class "A" that you want to test, and it makes use of a static class "B" that does something that you do not want to test, like hitting the database, class A is now hard to test.

class A
{
    // this is hard to test because of the static call through B
    public void MethodToTest() 
    {
         // ...
         B.HitTheDatabase();
         // ...
    }
}

There are ways around this, such as writing a wrapper around B and injecting it into A, or using the Moles framework

Seth Flowers
  • 8,990
  • 2
  • 29
  • 42