Using Moq ExpectSet
September 17th, 2008
I am trying out Moq, having used RhinoMocks a fair bit in the past.
I was having trouble using the ExpectSet method which verifies that a property has been set, and a google search found nothing that directly answered my question. I wanted to know how to verify that the value set is what was expected.
It turns out that you need to define a callback in which you have the assertion to verify that the property has been set to the correct value.
[TestMethod] public void TestAppleShiner() { // Mock the interface being passed to the class to be tested var fruit = new Mock<IFruit>(); // Define the expectation that the Colour property will be // set to Green fruit.ExpectSet(f=>f.Colour).Callback( setColor=>Assert.AreEqual("Green", setColor)).Verifiable(); // Run the test ApplePolisher applePolisher = new ApplePolisher(); applePolisher.Polish(fruit.Object); // Verify that the test passed (note .Verifiable on the ExpectSet) fruit.VerifyAll(); } public interface IFruit { string Colour { get; set; } } public class ApplePolisher { public void Polish(IFruit fruit) { fruit.Colour = "Green"; } }
After ExpectSet, call the Callback method giving the name of the variable to hold the passed in value, and then the assertion with regards to its value.


September 18th, 2008 at 8:59 am
[...] Using Moq ExpectSet - Damian Mehers gives a nice simple example of using the Moq Mocking Framework ExpectSet functionality. [...]
October 4th, 2008 at 6:29 am
Hey Daniel, Thanks for this. Just what I was looking for.
One thing though… (there always is isn’t there?). That moq.VerifyAll(); at the end of the test? I wouldn’t. if you set .Verifiable() on the expectation you can use .Verify() and it will check all expectations that you set .Verifiable() on. .VerifyAll() will check _all_ expectations.
I’ve had to wean myself off of MockBehaviour.Strict and .VerifyAll(). They seem like such a good idea until you refactor something and find out how brittle they make your tests.
All the best
October 4th, 2008 at 6:29 am
Oh, and stick with Moq, it’s brilliant.
October 8th, 2008 at 6:08 am
Btw, you can now use ExpectSet(f => f.Name, “kzu”)
October 8th, 2008 at 8:43 am
Fantastic - thanks Daniel.
/Damian
February 23rd, 2009 at 5:45 am
[...] Using Moq ExpectSet: Damian Mehers shows us how to use the ExpectSet method in Moq. [...]