在模拟方法(Moq)中更改参考参数的值
Changing values of reference parameter within mocked method (Moq)
当在另一个方法中创建参数时,如何设置 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
}
}
}
假设我想对 Insert() 方法进行单元测试。我如何设置业务逻辑的 Apply() 方法的模拟以接收任何 Response class 并让它填充 returning Response 对象并将 Success 设置为 true 以便其余代码可以 运行.
顺便说一句,我已将 Apply() 方法的 return 类型更改为 bool(而不是 Void),以使 Moq 简单地 return 为真,类似于以下内容:
mockMyBusinessLogic.Setup(x => x.Apply(It.IsAny<Response>()).Returns(true);
但是让一个方法做某事感觉很尴尬,return做某事(我更喜欢让方法只做一个或另一个)。
希望有一种看起来 "something" 如下的方式(使用 void 时):
mockMyBusinessLogic.Setup(
x => x.Apply(It.IsAny<Response>()).Callback(()
=> new Response { Success = true });
您可以使用 Callback<T>(Action<T>)
方法访问传递给模拟调用的参数:
mockMyBusinessLogic
.Setup(x => x.Apply(It.IsAny<Response>())
.Callback<Response>(r => r.Success = true);
当在另一个方法中创建参数时,如何设置 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
}
}
}
假设我想对 Insert() 方法进行单元测试。我如何设置业务逻辑的 Apply() 方法的模拟以接收任何 Response class 并让它填充 returning Response 对象并将 Success 设置为 true 以便其余代码可以 运行.
顺便说一句,我已将 Apply() 方法的 return 类型更改为 bool(而不是 Void),以使 Moq 简单地 return 为真,类似于以下内容:
mockMyBusinessLogic.Setup(x => x.Apply(It.IsAny<Response>()).Returns(true);
但是让一个方法做某事感觉很尴尬,return做某事(我更喜欢让方法只做一个或另一个)。
希望有一种看起来 "something" 如下的方式(使用 void 时):
mockMyBusinessLogic.Setup(
x => x.Apply(It.IsAny<Response>()).Callback(()
=> new Response { Success = true });
您可以使用 Callback<T>(Action<T>)
方法访问传递给模拟调用的参数:
mockMyBusinessLogic
.Setup(x => x.Apply(It.IsAny<Response>())
.Callback<Response>(r => r.Success = true);