0

a class like this

public abstract class TT
{
    public virtual int ID { get; set; }
}
public class X
{
    public void F(TT t)
    {
        t.ID = 100;
    }
}

the function X.F use TT to do something. I what test F .

so

[TestMethod]
public void T()
{
    var t = new Mock<TT>();
    new X().F(t.Object);
    Assert.AreEqual(100, t.Object.ID);
}

but the t.Object.ID is always "0". when I set ID as not virtual, it's passed.

so, why does it? and how can i make the virtual property can be writed ?

2 Answers 2

2

The issue is with how Moq actually builds the mocks. Since in this case it does it by extending your class and overriding, the property marked as virtual is one that will be handled by Moq.

So I believe what is missing in your implementation is the setup for the property:

t.SetupProperty(f => f.ID);

And you can also have Moq set up all your properties using:

t.SetupAllProperties();

A lot of useful examples can be found here: http://code.google.com/p/moq/wiki/QuickStart

0
2

Because TT is a class with virtual methods (rather than an interface) these is another option.

As mentioned in Pablo's answer, Moq extends your class, overrding the virtual property. However, there is an option, CallBase, which tells Moq to use the original (overridden) version where there are no setups defined.

If one sets CallBase to true on the mock, the original property will be called and there is no need to set up the property explicitly.

[TestMethod]
public void T() {
    var t = new Mock<TT>() { CallBase = true };
    new X().F(t.Object);
    Assert.AreEqual(100, t.Object.ID);
}

This is not a better answer than using SetupUpAllProperties() but is very useful in situations where one wants to use setups for only some of the functionality.

1
  • Another great alternative indeed! We should get shared credit on this one :) Oct 12, 2012 at 5:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.