R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234414

How can I mock Assembly?

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?

Upvotes: 5

Views: 5319

Answers (2)

Brett
Brett

Reputation: 944

13 years later, mocking assemblies with Moq seems to work just fine.

var assembly = new Mock<Assembly>();
assembly
    .Setup(a => a.GetTypes())
    .Returns( new [] { typeof(SomeType), } );

Then

Assert.Contains(typeof(SomeType), assembly.Object.GetTypes());

Upvotes: 0

Francis B.
Francis B.

Reputation: 7208

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
}

Upvotes: 9

Related Questions