Home > Backend Development > C++ > Can Moq Assign Values to Out Parameters?

Can Moq Assign Values to Out Parameters?

DDD
Release: 2025-01-18 05:31:13
Original
734 people have browsed it

Can Moq Assign Values to Out Parameters?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template