Question

Could someone explain why both tests using the latest versions of Moq and Rhino.Mocks frameworks fail complaining that Bar is not a virtual/overridable method:

public interface IFoo
{
    string Bar();
}

public class Foo : IFoo
{
    public string Bar()
    {
        return "Bar";
    }
}

[TestMethod]
public void MoqTest()
{
    var foo = new Mock<Foo>();
    foo.Setup(f => f.Bar()).Returns("abc");
    Assert.AreEqual("abc", foo.Object.Bar());
}

[TestMethod]
public void RhinoTest()
{
    var foo = new MockRepository().PartialMock<Foo>();
    foo.Expect(f => f.Bar()).Return("abc");
    foo.Replay();
    Assert.AreEqual("abc", foo.Bar());
}

If I declare Bar method as virtual both tests pass. I don't understand why I have to declare Bar as virtual. Isn't it already virtual? It comes from the interface.

Was it helpful?

Solution

Virtual is part of the class not the interface, so if you wish to override the method on the class Foo you will need to declare it as virtual.

However as Krzysztof mentions if all you need are the methods on the interface IFoo then you should mock the interface.

OTHER TIPS

Because you're mocking Foo class. Mock IFoo intefrace instead

var foo = new MockRepository().PartialMock<IFoo>();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top