Setting Reference Parameters in Moq

A colleague just came to me asking for advice on how to set the value of a referenced parameter with Moq; after nearly berating him for not checking Google I was surprised to find examples out there don’t actually make it that obvious to the uninitiated.

For the purposes of this quick post I’ve created a dummy interface and associated method to mock, and then a quick method to test the mocked interface. This might seem long-winded but it’s standard measure in our team to ensure it’s firmly covered.

1
2
3
4
public interface ISomeThingToMock
{
  void MockWithRefParam(int someOtherParam, StringBuilder stringBuilder);
}

Let’s show how a class might implement the interface:

1
2
3
4
5
6
public class SomeThingToMock : ISomeThingToMock
{
  public void MockWithRefParam(int someOtherParam, StringBuilder stringBuilder) {
      stringBuilder.Append("ThisWasNotMocked");
  }
}

Now I’m going to create a quick method that uses the above so our example is obvious:

1
2
3
4
5
6
7
8
public class MockTester
{
  public string TestThis(ISomeThingToMock myMock) {
      StringBuilder s = new StringBuilder();
      myMock.MockWithRefParam(10, s);
      return s.ToString();
  }
}

Using NUnit as our testing framework together with Moq this is a quick example test to prove our theory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System.Text;
using NUnit.Framework;
using Moq;
using ReferenceParameterMoqExample;

namespace ReferenceParameterMoqExampleTests
{
 [TestFixture]
  public class SomeThingToMockTests
  {
      private MockTester _MockTester;
      private Mock _SomeThingToMock;

     [Setup]
      public void TestSetup() {
          _MockTester = new MockTester();
          _SomeThingToMock = new Mock();
      }

     [Test]
      public void TestThis_WithRefParam_ReturnsSpecificValue() {
          _SomeThingToMock
              .Setup(x => x.MockWithRefParam(It.IsAny(), It.IsAny()))
              .Callback((int i, StringBuilder s) => s.Append("ThisWasMocked"));

          Assert.AreEqual("ThisWasMocked", _MockTester.TestThis(_SomeThingToMock.Object));
      }
  }
}

Comments