'C# Moq: How to I create a create a Mock that returns the input with a field adjusted

I am trying to mock a sub-process for my tests. I know I can return the input to the function I am mocking as such:

Mock<MockedObject> mock = new Mock<MockedObject>();
mock.Setup(x => x.MockedFunction(It.IsAny<FunctionInput>())) 
    .Returns<Function>(x => x);

What I want to be returned is the input value with one field changed to a hard coded value, but I am unsure how to do this. Thanks



Solution 1:[1]

Returns has an overload that takes a Func<T, TResult> which seems to be what you're looking for.

[TestMethod]
public void Test()
{
    var mock = new Mock<MockedObject>();
    mock.Setup(x => x.MockedFunction(It.IsAny<FunctionInput>()))
        .Returns<FunctionInput>(x =>
        {
            x.Name = "Bob";
            return x;
        });

    var result = mock.Object.MockedFunction(new FunctionInput { Name = "Nyle" });
    Assert.AreEqual("Bob", result.Name);
}

For this example, I defined MockedObject and FunctionInput as follows.

public class MockedObject
{
    public virtual FunctionInput MockedFunction(FunctionInput functionInput)
    {
        throw new NotImplementedException();
    }
}


public class FunctionInput
{
    public string Name { get; set; }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Batesias