Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you mock an object that implements an interface AND an abstract class?

Is it possible to use Moq to mock an object that implements an interface and abstract class?

I.e.:

public class MyClass: SomeAbstractClass, IMyClass

Can you mock this?

like image 213
mrblah Avatar asked Dec 28 '09 13:12

mrblah


1 Answers

You can mock any interface, and any abstract or virtual members. That's basically it.

This means that the following are absolutely possible:

var imock = new Mock<IMyClass>();
var aMock = new Mock<SomeAbstractClass>();

If the members inherited from SomeAbstractClass aren't sealed, you can also mock MyClass:

var mcMock = new Mock<MyClass>();

Whether this makes sense or not depends on the implementation of MyClass. Let's say that SomeAbstractClass is defined like this:

public abstract class SomeAbstractClass
{
    public abstract string GetStuff();
}

If the GetStuff method in MyClass is implemented like this, you can still override it:

public override string GetStuff()
{
    return "Foo";
}

This would allow you to write:

mcMock.Setup(x => x.GetStuff()).Returns("Bar");

since unless explicitly sealed, GetStuff is still virtual. However, had you written GetStuff like this:

public override sealed string GetStuff()
{
    return "Baz";
}

You wouldn't be able to mock it. In that case, you would get an exception from Moq stating that it's an invalid override of a non-virtual member (since it's now sealed).

like image 89
Mark Seemann Avatar answered Sep 27 '22 21:09

Mark Seemann