For a method like:
protected virtual bool DoSomething(string str) { }
I usually mock it through:
var mockModule = new Mock<MyClass> { CallBase = true };
mockModule.Protected().Setup<bool>("DoSomething", ItExpr.IsAny<string>()).Returns(true);
But for a method like:
protected virtual bool DoSomething(out string str) { }
How can I mock it?
It can be done since moq 4.8.0-rc1 (2017-12-08). You can use ItExpr.Ref<string>.IsAny
for match any value for ref
or out
parameters. In your case:
mockModule.Protected().Setup<bool>("DoSomething", ItExpr.Ref<string>.IsAny).Returns(true);
Full example with mocking the out parameter:
[TestClass]
public class OutProtectedMockFixture
{
delegate void DoSomethingCallback(out string str);
[TestMethod]
public void test()
{
// Arrange
string str;
var classUnderTest = new Mock<SomeClass>();
classUnderTest.Protected().Setup<bool>("DoSomething", ItExpr.Ref<string>.IsAny)
.Callback(new DoSomethingCallback((out string stri) =>
{
stri = "test";
})).Returns(true);
// Act
var res = classUnderTest.Object.foo(out str);
// Assert
Assert.AreEqual("test", str);
Assert.IsTrue(res);
}
}
public class SomeClass
{
public bool foo(out string str)
{
return DoSomething(out str);
}
protected virtual bool DoSomething(out string str)
{
str = "boo";
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With