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.

6 Responses to “Using Moq ExpectSet”

  1. Reflective Perspective - Chris Alcock » The Morning Brew #182 Says:

    [...] Using Moq ExpectSet - Damian Mehers gives a nice simple example of using the Moq Mocking Framework ExpectSet functionality. [...]

  2. Hamish Says:

    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

  3. Hamish Says:

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

  4. Daniel Cazzulino Says:

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

    :)

  5. dmehers Says:

    Fantastic - thanks Daniel.

    /Damian

  6. Weekly Web Nuggets #30 : Code Monkey Labs Says:

    [...] Using Moq ExpectSet: Damian Mehers shows us how to use the ExpectSet method in Moq. [...]

Leave a Reply