Category Archives: unit testing

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.

Handling background threads using NUnit and Rhino Mocks

I’ve just started using NUnit and Rhino Mocks, so this is not necessarily the best way to do things, but it works for me.

I have a class which has a method which kicks off a background thread.  This thread has an infinite loop — for each loop it accepts a request and services the request.

I needed to test an instance of the class, for one specific incoming request.  There are two issues — how to know when the object’s background thread has finished servicing the request, and how to stop the background thread from looping back and accepting another request.

This is what I ended up doing:

public class ServerTest {

  public void SomeTest() {

    bool done = false;

    MockRepository mocks = new MockRepository();

    using(mocks.Record()) {

      // ... lots of 'Expects'

      // This is the final call which gets made in the background thread
      // to complete the handling of the request
      Expect.Call(someObject.LastMethod).Do((Expect.Action)delegate() {
        done = true;
    using(mocks.Playback()) {
      Server server = new Server();
      int count = 0;
      while(!done && count < 10) {

The key point is that in the test’s action associated with the last method that gets invoked as part of your background thread’s processing loop, you need to set a flag so that the test knows that the last method has executed, and also abort the current thread so that the background thread doesn’t loop back, and consume another request.