piątek, 9 maja 2008

How to test static method call in c# without TypeMock

If you think - like me - that TDD is not only testing, but also design process, you probably are using Rhino Mocks or any other mocking tool that is based on interface/virtual methods implementation. But how can one mock a call to static method like

File.Open("...", FileMode.Open);

The only method until now (for me) was to use Typemock. But until you buy a paid version, you cannot use it without typing method names as string - which I don't like.

After long long long searching I think I found an alternative - Delegates.

Lets see an example (in c# 3.5):

    public class SomeClass
public Func<string, FileMode, Stream> FileOpen = File.Open;

public void DoSomethingWithFile(string path)
using (Stream s = FileOpen(path, FileMode.Open))

As you see, I placed a public delegate to File.Open which I can change later in my test

public void TestDoSomethingWithFile()
SomeClass sc = new SomeClass();
string testFile = Path.GetTempFileName();
//...fill this testFile

            sc.FileOpen = delegate { return File.OpenRead(testFile); };
//Asserts here

What is great about such pattern is that you can treat those delegates in class as references in dll file.
Another great thing is that you can use Dependency Injection to inject static(or not) methods to the class.


And thats it. So simple right?
Ummm, but what about performance, delegates can't work as fast as static calls.
Well, I'll show you some benchmarks later.

Brak komentarzy: