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.
public interface ISomeThingToMock
{
void MockWithRefParam(int someOtherParam, StringBuilder stringBuilder);
}
Let's show how a class might implement the interface:
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:
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:
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));
}
}
}