Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq: Setup a property without setter?

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.

like image 603
Sven Avatar asked Oct 27 '10 23:10

Sven


People also ask

How do you set a mock object property?

You can set the mock object property to the value returned by the mock object method. To achieve this, specify separate behaviors for the method and the property. You can specify one behavior at a time. For more information about mock object behavior, see Specify Mock Object Behavior.

How do you private a mock variable in C#?

Make a protected getter for this private variable, and override it in testing subclass to return a mock object instead of the actual private variable. Create a protected factory method for creating ISnapshot object, and override it in testing subclass to return an instance of a mock object instead of the real one.

What does Moq setup do?

Moq, how it works The idea is to create a concrete implementation of an interface and control how certain methods on that interface responds when called. This will allow us to essentially test all of the paths through code.

Can you mock a class with Moq?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.


1 Answers

You can use .SetupGet on your mock object.

eg.

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

See here for further details.

like image 90
Jim Johnson Avatar answered Sep 21 '22 16:09

Jim Johnson