Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock Assembly?

Tags:

.net

mocking

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?

like image 949
R. Martinho Fernandes Avatar asked Sep 03 '09 20:09

R. Martinho Fernandes


1 Answers

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
}
like image 149
Francis B. Avatar answered Oct 21 '22 01:10

Francis B.