【发布时间】:2015-12-14 11:47:26
【问题描述】:
我有以下课程,我正在尝试测试 AddRecordToQueue 方法。
我正在使用 Moq 在 AddRecordToQueue 方法中模拟 AddToQueue 方法的结果。
AddToQueue 方法返回一个布尔值,所以我试图用真值模拟结果
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);
}
}
我似乎无法将 moq 结果设置为 true。谁能告诉我我错过了什么
谢谢
【问题讨论】:
-
不是在机器上进行测试,但我在这里看到了两件事。 1. 在获得对
.Object的引用之前,您应该先Setup; 2.在Setup中,将参数设置为null,并为空,尝试使用Setup(e => e.AddToQueue(It.IsAny(), Is.IsAny())).Returns(true)) -
其实在获取Object之前不需要做Setup
标签: c# unit-testing moq