Damian Mehers' Blog Xamarin from Geneva, Switzerland.


Using Moq ExpectSet

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.

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
        setColor=>Assert.AreEqual("Green", setColor)).Verifiable();

    // Run the test
    ApplePolisher applePolisher = new ApplePolisher();

    // Verify that the test passed (note .Verifiable on the ExpectSet)

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.
Comments (4) Trackbacks (2)
  1. 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

  2. Oh, and stick with Moq, it’s brilliant.

  3. Btw, you can now use ExpectSet(f => f.Name, “kzu”)


  4. Fantastic – thanks Daniel.


Leave a comment