05 August 2006

Mocking static methods

Yes, the title is correct. Mocking static methods in .NET is possible with TypeMock library. There is no need to redesign you classes just to test them. In fact there is no need to write additional code to your classes. This is possible because TypeMock uses profiler's API to handle execution of methods and creation of classes. For a list of features look here.
Using TypeMock is pretty easy. In my previous post about NHibernate session management I'm using a static method to create appropriate session manager (take a look at GenericDAO constructor). The test of the constructor may be something like:


[TestFixture]
public class GenericDAOTest
{
    [SetUp]
    public void InitTest()
    {
        MockManager.Init();
        //ormManagerMock = MockManager.Mock(typeof(PerRequestWebManager));
        ormManagerFactory = MockManager.Mock(typeof(OrmManagerFactory));
    }
 
    //private Mock ormManagerMock;
    private Mock ormManagerFactory;
    private GenericDAO<Article> articleDAO;
 
    [TearDown]
    public void FinalizeTest()
    {
        MockManager.ClearAll();
    }
 
    [Test]
    public void TestDAOConstructor()
    {
        ormManagerFactory.ExpectAndReturn("GetInstance",
            new PerRequestWebManager());
 
        articleDAO = new GenericDAO<Article>();
 
        MockManager.Verify();
    }
}
 

Although TypeMock is powerful and easy to use library, there are some disadvantages. For example in the free version, when the test is started for first time, a popup dialog appears and invites you to buy the product. Also not all of the .NET types can be mocked (for more information take a look at this thread).

No comments: