public interface IService
{
void DoIt(out string a);
}
[TestMethod]
public void Test()
{
var service = new Mock<IService>();
var a = "output value";
service.Setup(s => s.DoIt(out a));
string b;
service.Object.DoIt(out b);
Assert.AreEqual("output value", b);
}
[TestMethod]
public void TestForOutParameterInMoq()
{
//Arrange
var _mockParameterManager = new Mock<IParameterManager>();
Mock<IParameter> mockParameter = new Mock<IParameter>();
//Parameter affectation should be useless but is not. It's really used by Moq
IParameter parameter = mockParameter.Object;
//Mock method used in UpperParameterManager
_mockParameterManager.Setup(x => x.OutMethod(out parameter));
//Act with the real instance
UpperParameterManager.UpperOutMethod(out parameter);
//Assert that method used on the out parameter of inner out method are really called
mockParameter.Verify(x => x.FunctionCalledInOutMethodAfterInnerOutMethod(), Times.Once());
}
[TestMethod]
public void TestForOutParameterInMoq1()
{
var mock = new Mock<IFoo>();
// out arguments
var outString = "ack"; // TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);
// ref arguments
var instance = new Bar1(); // Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);
}
[TestMethod]
public void TestForOutParameterInMoq3()
{
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.DoSomething("ping")).Returns(true);
// out arguments
var outString = "ack";
// TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);
// ref arguments
var instance = new Bar1();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);
// access invocation arguments when returning a value
mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns((string s) => s.ToLower()); // Multiple parameters overloads available
// throwing when invoked
mock.Setup(foo => foo.DoSomething("reset")).Throws<InvalidOperationException>();
mock.Setup(foo => foo.DoSomething("")).Throws(new ArgumentException("command");
// lazy evaluating return value
mock.Setup(foo => foo.GetCount()).Returns(() => count);
// returning different values on each invocation var mock = new Mock<IFoo>();
var calls = 0; mock.Setup(foo => foo.GetCountThing()).Returns(() => calls).Callback(() => calls++);
// returns 0 on first invocation, 1 on the next, and so on
Console.WriteLine(mock.Object.GetCountThing());
}