Moq 设置方法返回值 [英] Moq setting method return value
问题描述
我有以下课程,我正在尝试测试 AddRecordToQueue 方法.
I have the below class, and I am trying to test the method AddRecordToQueue.
我正在使用 Moq 来模拟 AddRecordToQueue 方法中的 AddToQueue 方法的结果.
I am using Moq to mock the result of the the AddToQueue method within the AddRecordToQueue method.
AddToQueue 方法返回一个布尔值,所以我试图用真值模拟结果
The AddToQueue method returns a boolean, so i am trying to mock the result with a true value
public class Test
{
private readonly IRabbitMqConnection rabbitMqConnection;
public Test(IRabbitMqConnection rabbitMqConnection)
{
this.rabbitMqConnection = rabbitMqConnection;
}
public bool AddRecordToQueue(string messageExchange, object data)
{
var jsonified = JsonConvert.SerializeObject(data);
var customerBuffer = Encoding.UTF8.GetBytes(jsonified);
var result = this.rabbitMqConnection.AddToQueue(customerBuffer, messageExchange);
return result;
}
}
我的测试类如下所示.
[TestClass]
public class TestCon
{
[TestMethod]
public void MockTest()
{
Moq.Mock<IRabbitMqConnection> rabbitConection = new Moq.Mock<IRabbitMqConnection>();
var draftContactsManager = new Test(rabbitConection.Object);
rabbitConection.Setup(e => e.AddToQueue(null, string.Empty)).Returns((bool res) => true);
var result = draftContactsManager.AddRecordToQueue("someExchange", null);
Assert.IsTrue(result);
}
}
我似乎无法将起订量结果设置为 true.谁能告诉我我缺少什么
I cant seem to set the moq result as true. Can anyone advise what I am missing
谢谢
推荐答案
我认为您需要将 Returns
更改为仅返回 true 而不是 lambda.像这样:
I think that you need to change the Returns
to just return true instead of the lambda. Like this:
rabbitConection.Setup(e => e.AddToQueue(null, string.Empty)).Returns(true)
如果还是不行,可能是参数不匹配.您正在传入 "someExchange"
但模拟是为 string.Empty 设置的.如果您不确定将使用什么值,您可以使用 It.IsAny
方法来解决这个问题.
If this still doesn't work then it is probably due to the parameters not matching. You are passing in "someExchange"
but the mock is set up for string.Empty. If you aren't sure what values will be used you could use the It.IsAny
method to get around this.
rabbitConection.Setup(e => e.AddToQueue(It.IsAny<byte[]>(), It.IsAny<string>())).Returns(true)
这篇关于Moq 设置方法返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!