Moq SetupSet on property

moq

Solution

Since you're creating your mock with `new Mock<IDispatcherTimer>()`, it defaults to `Loose` mock behavior. This means that the mock object will not complain when it is used in a way that was not specified via a `Setup` method. Using the constructor overload that accepts a `MockBehavior` enumeration and specifying `Strict` will make the code behave like you'd expect. It looks like that's how you're expecting to use it judging by the `Setup` calls; they would be unnecessary if you were using loose mocks.

Alternatively you can keep the loose mock and change the `SetupSet` for the `Interval` to be a `VerifySet` after you expect it to be set. I.e.:

var ageService = new AgeUpdatingService(timer);

TimeSpan interval = TimeSpan.FromMinutes(10);
TimeSpan tolerance = TimeSpan.FromMilliseconds(100)

ageService.AddParticipant(new Participant{ DOB = DateTime.Now + interval });

mockTimer.VerifySet(m => m.Interval = It.IsInRange(
    interval - tolerance, interval + tolerance, Range.Inclusive));

This is like a test assertion, meaning if a set of the `Interval` property never happened when this is invoked, it would throw a `MoqException` and fail the test.

Problem

i am trying to learn to use Moq (4) to test the C# code below. I was hoping that by setting ``` mockTimer.SetupSet(m => m.Interval = It.IsInRange( interval - shorter, interval + longer, Range.Inclusive)); ``` before calling the method which assigns the interval property a value (ageService.AddParticipant method), the test would throw when an incorrect value was assigned. However, even when a value well outside the specified range is assigned to the Interval property within the AddParticipant method, the test passes. I also find timer.Interval has a value of 0 after executing the AddParticipant method, even though I can see this property being assigned a non-zero value when stepping through the AddParticipant method. ``` [TestMethod] public void TestAgeUpdatingStartOnAdd() { var mockTimer = new Mock<IDispatcherTimer>(); mockTimer.SetupProperty(m => m.Interval); mockTimer.Setup(m => m.Start()); mockTimer.Setup(m => m.Stop()); IDispatcherTimer timer = mockTimer.Object; var ageService = new AgeUpdatingService(timer); TimeSpan interval = TimeSpan.FromMinutes(10); TimeSpan tolerance = TimeSpan.FromMilliseconds(100) mockTimer.SetupSet(m => m.Interval = It.IsInRange( interval - tolerance, interval + tolerance, Range.Inclusive)); ageService.AddParticipant(new Participant{ DOB = DateTime.Now + interval }); ``` What am I doing wrong? Am I missing the point of the SetupSet method all together (and therefore should just stick to examining the properties on the timer object after executing the function, which seemed to work prior to placing the SetupSet method in the code)? If so, could you please explain what SetupSet exists for. Thank you.

Original source