嗨,我有以下接口(interface)及其实现。现在,我想对 Send()
进行单元测试该方法实际上会将消息推送到队列中。
由于我是 MoQ 的新手,不知道如何完成它。
public interface IAdapter
{
IChannel UseQueue(QueueDetail queueDetail);
}
public interface IChannel
{
void Send(string key, byte[] message);
}
public class AdapternServiceBus : IAdapter
{
readonly IConnection connection;
readonly IModel channel;
public AdapternServiceBus(IConnection connection, IModel channel)
{
this.connection = connection;
this.channel = channel;
}
public IChannel BindAndUseQueue(QueueDetail queueDetail)
{
// Logic of creating and binding queue
return new ServiceBusChannel(this, queueDetail.QueueName);
}
public IModel GetChannel()
{
return channel;
}
}
public class ServiceBusChannel : IChannel
{
readonly string containerName;
IModel channel;
public ServiceBusChannel(AdapternServiceBus adapter, string containerName)
{
this.containerName = containerName;
channel = adapter.GetChannel();
}
public void Send(string key, byte[] message)
{
// Publish the message
channel.BasicPublish(exchangeName, key, null, message);
}
}
这里通过工厂,我们决定我们需要连接哪种类型的框架,在工厂内,我们打开一个传递给下一个类的连接,以便可以使用它来创建和绑定(bind)队列。
IChannel
的实现是将用于实际与队列和主题交谈的主要类。
最佳答案
您想测试 Send
ServiceBusChannel
中的方法类(class)。
因此,在您的测试中,您应该实例化这个实际的具体类。
实例化 ServiceBusChannel
, 你需要一个 AdapterServiceBus
允许您设置您的channel
多变的。
在这里,问题是你依赖于一个具体的 AdapterServiceBus 类,所以你不能模拟它。您应该依赖于公开您要模拟的实际行为的接口(interface)。
像 IAdpaterServiceBus 这样声明 GetChannel();
, (编辑)或声明GetChannel()
作为您现有的IAdapter
的一种方法交互)。
然后你可以模拟这个:
var mockedAdapter = new Mock<IAdapterServiceBus>();
或者
var mockedAdapter = new Mock<IAdapter>(); // if you added GetChannel() to IAdapter
然后模拟 GetChannel() 的行为:
mockedAdapter.Setup(x => x.GetChannel())
.Returns( /* some mocked string value for your channel */);
然后您可以将其传递给您的 ServiceBusChannel 构造函数(已修改,使其接受抽象
IAdapterServiceBus
(或 IAdapter
)而不是具体实例)var service = new ServiceBusChannel(mockedAdapter.Object, containerName);
关于c# - 使用 MOQ 嵌套类和接口(interface) C# 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197897/