Output parameter assignment in Moq
Question:
Can Moq be used to assign values to output parameters?
Answer:
Yes, you can use Moq 3.0 and above to assign values to output parameters. Here’s how:
For output parameters:
<code class="language-csharp">public interface IService { void DoSomething(out string a); } [TestMethod] public void Test() { var service = new Mock<IService>(); string expectedValue = "value"; service.Setup(s => s.DoSomething(out expectedValue)); string actualValue; service.Object.DoSomething(out actualValue); Assert.AreEqual(expectedValue, actualValue); }</code>
Moq records the value assigned to an output parameter during setup and returns that value during testing.
For reference parameters:
Moq does not currently support this feature. However, you can use Rhino Mocks, or use a constrained Action as a workaround:
Use constrained Action:
<code class="language-csharp">public interface IService { void DoSomething(ref string a); } [TestMethod] public void Test() { var service = new Mock<IService>(); string value = "initial"; service.Setup(s => s.DoSomething(ref It.Ref<string>.IsAny)) .Callback<string>(s => s = "expectedValue"); service.Object.DoSomething(ref value); Assert.AreEqual("expectedValue", value); }</code>
Here we use the It.Ref<T>.IsAny
constraint to match any input reference parameter and set its value in the callback.
The above is the detailed content of Can Moq Assign Values to Out Parameters?. For more information, please follow other related articles on the PHP Chinese website!