2

Can this be done? Here is the method I'm testing:

public void SaveAvatarToFileSystem()
{
  Directory.CreateDirectory(AvatarDirectory);
  _file.SaveAs(FormattedFileName);
}

In my unit test, I'm using Rhino.Mocks and I want to verify that _file.SaveAs() was called. I've mocked out _file (which is an HttpPostedFileBase object) and injected it into this method's class constructor. I want to run this unit test, but not actually have the Directory.CreateDirectory call get made. Is this possible?

Lee Warner
  • 2,543
  • 4
  • 30
  • 45
  • 5
    possible duplicate of [Mocking Static methods using Rhino.Mocks](http://stackoverflow.com/questions/540239/mocking-static-methods-using-rhino-mocks) – Kirk Woll Nov 03 '10 at 18:54

3 Answers3

3

It is not possible to mock a static method using Rhino Mocks.

However, it is possible to do this. Microsoft Moles and TypeMock have this capability.

I have tried using Moles, and it works alright. It generates a mock assembly for you, and you are able to replace a static method at runtime with a delegate.

Community
  • 1
  • 1
driis
  • 161,458
  • 45
  • 265
  • 341
2

Its not possible to mock a static method using Rhino Mocks. What I would do is isolate the static method in "protected internal virtual" method in the class. Then what you can do is mock the "Class Under Test" and mock the "CreateAvatarDirectory" method. Then call the "SaveAvatarToFileSystem" method and verify that the code called your mocked "CreateAvatarDirectory" method.

Its a very handy trick that allows you to isolate methods in your class under test and assert they were called by other methods in the same class. Hope that helps!

public void SaveAvatarToFileSystem()
{
    CreateAvatarDirectory();
    _file.SaveAs(FormattedFileName);
}

protected internal virtual void CreateAvatarDirectory()
{
    Directory.CreateDirectory(AvatarDirectory);
}
Matthew Kubicina
  • 1,104
  • 1
  • 10
  • 18
0

You could write or using an existing wrapper for the static class (in the case above maybe System.IO.Abstractions will help).

Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81