在模拟方法(Moq)中更改参考参数的值

Ste*_*nar 5 c# unit-testing moq mocking

当在另一个方法中创建参数时,如何设置Moq以更改内部方法参数的值.例如(下面的简化代码):

public class Response
{ 
    public bool Success { get; set; }
    public string[] Messages {get; set;}
}

public class MyBusinessLogic
{
    public void Apply(Response response);
}


public class MyService
{
    private readonly MyBusinessLogic _businessLogic;

    ....

    public Response Insert()
    {
        var response = new Response();   // Creates the response inside here
        _businessLogic.Apply(response);

        if (response.Success) 
        {
            // Do more stuff
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

假设我想对Insert()方法进行单元测试.如何设置Business Logic的Apply()方法的模拟以接收任何Response类,并让它填充返回的Response对象,并将Success设置为true,以便其余代码可以运行.

顺便说一句,我已经改变了应用()方法的返回类型为布尔(而不是空隙),以有订货数量简单地返回true,类似于下面:

mockMyBusinessLogic.Setup(x => x.Apply(It.IsAny<Response>()).Returns(true);
Run Code Online (Sandbox Code Playgroud)

但是,如果有一个方法可以做某事,并返回一些东西(我更喜欢让方法只做一个或另一个),这感觉很尴尬.

希望有一种方式可能看起来像下面的东西(使用void时):

mockMyBusinessLogic.Setup(
   x => x.Apply(It.IsAny<Response>()).Callback(() 
           => new Response { Success = true });
Run Code Online (Sandbox Code Playgroud)

k.m*_*k.m 8

您可以使用Callback<T>(Action<T>)方法访问传递给模拟调用的参数:

mockMyBusinessLogic
    .Setup(x => x.Apply(It.IsAny<Response>())
    .Callback<Response>(r => r.Success = true);
Run Code Online (Sandbox Code Playgroud)