It really depends on what Bar
is. If it's something simple then your Foo
method is already testable, you just need to specify your expectations and invoke it statically, e.g.:
Assert.IsTrue( FooContainer.Foo() );
But if Bar
encapsulates, say, your database access layer, then you can't test Foo
without a real database, which is why (thanks @ysolik), static methods are death to testability. Or, in the words of Michael Feathers, "don't hide a TUF in a TUC" (TUF stands for a test-unfriendly feature, TUC stands for a test-unfriendly construct). If Bar
is indeed test-unfriendly, then sorry, it doesn't work well without making Foo
an instance method. You would need to redesign your code first:
public class FooContainer {
public bool Foo() {
var bar = new Bar();
//...
}
}
When Foo
is no longer static, you can invoke it on an instance of FooContainer
:
var container = new FooContainer();
Assert.IsTrue( container.Foo() );
The next step is to extract an interface from Bar
(let's call it IBar
) and inject it into FooContainer
:
public class FooContainer {
private readonly IBar m_bar;
public FooContainer( IBar bar ) { m_bar = bar; }
public bool Foo() {
// don't create another Bar, use m_bar
}
}
Now you can mock/stub IBar
with your favourite isolation framework and test your FooContainer
code in isolation from its dependencies.