-
Notifications
You must be signed in to change notification settings - Fork 3
Out and ref parameters
As of 2.0.4, both out and ref parameters are supported. This works with two special extensions to the method and function behaviours that provide a way to input those values. Consider the following example:
public interface IConverter
{
bool TryParse(string text, out int value);
}
public class ConverterService
{
private readonly IConverter _converter;
public ConverterService(IConverter converter)
{
_converter = converter;
}
public int GetValue(string text)
{
int value;
return _converter.TryParse(text, out value) ? value : -1;
}
}
The above attempts to parse a string to get a value. The IConverter would provide this behaviour, so we are going to mock this to test the service:
[TestClass]
public class ConverterServiceTests : TestBase<ConverterService>
{
[TestMethod]
public void GetValueReturnsIntFromOutArg()
{
int value;
MockFor<IConverter>().Setup(c => c.TryParse("123", out value)).WithOutArgs(123).Returns(true);
var result = Subject.GetValue("123");
Assert.AreEqual(123, result);
}
}
Here, the WithOutArgs provides the mechanism to pass in the expected out value when the function is called. The ref process is exactly the same but you call WithRefArgs instead.
Some things to observe. Firstly the order of the values passed to WithOutArgs or WithRefArgs must match the order of the method signature. Secondly, due to the DispatcherProxy and RealProxy classes used under the hood, verifying calls with out and/or ref parameters will not work. This is because the values will not be available when the calls are made.