views:

28

answers:

1

Hi, I have following class:

public class PairOfDice
{
    private Dice d1,d2;
    public int Value 
    {
       get { return d1.Value + d2.Value; }
    }
}

Now I would like to use a PairOfDice in my test which returns the value 1, although I use random values in my real dice:

[Test]
public void DoOneStep ()
{
    var mock = new Mock<PairOfDice>();
    mock.Setup(x => x.Value).Return(2);
    PairOfDice d = mock.Object;
    Assert.AreEqual(1, d.Value);
}

Unfortunately I get a Invalid setup on non-overridable member error. What can I do in this situation?

Please note, that this is my first try to implement Unit-Tests.

+1  A: 

Your problem is because it's not virtual. Not because you don't have a setter.

Moq cannot build up a Proxy because it cannot override your property. You either need to use an Interface, virtual method, or abstract method.

Aren
Is there a disadvantage setting this property to virtual?
BeatMe
Only if you consider sub-classes `override`-ing that function a risk. Basically nothing noteworthy unless it's a super secure function you can't trust other classes to get right, however those you shouldn't be mocking anyway as they wouldn't be public.
Aren