tags:

views:

125

answers:

1

Is it possible to mock the Assembly class?

If so, using what framework, and how?

If not, how would do go about writing tests for code that uses Assembly?

+1  A: 

TypeMock is very powerful. I guess it can do it. For the other mock frameworks like Moq or Rhino, you will need to use another strategy.

Strategy for Rhino or Moq:

Per example: You are using the Asssembly class to get the assembly full name.

public class YourClass
{
    public string GetFullName()
    {
        Assembly ass = Assembly.GetExecutingAssembly();
        return ass.FullName;
    }
}

The Assembly class derived from the interface _Assembly. So, instead of using Assembly directly, you can inject the interface. Then, it is easy to mock the interface for your test.

The modified class:

public class YourClass
{
    private _Assembly _assbl;
    public YourClass(_Assembly assbl)
    {
        _assbl = assbl;
    }

    public string GetFullName()
    {
        return _assbl.FullName;
    }
}

In your test, you mock _Assembly:

public void TestDoSomething()
{
    var assbl = MockRepository.GenerateStub<_Assembly>();

    YourClass yc = new YourClass(assbl);
    string fullName = yc.GetFullName();

    //Test conditions
}
Francis B.
It does. Can you explain how would I do it in a "traditional" mock framework (like Moq or Rhino)?
Martinho Fernandes
Oh, I didn't knew about this "hidden" `_Assembly` interface. Thanks. If I did, I wouldn't have asked the question. I guess that if Assembly didn't implement this interface I could have created one myself (`IAssembly`) and write a wrapper that implements it and uses the `Assembly` implementation, is that correct?
Martinho Fernandes
@ Martinho: That's correct
Francis B.