c# - 使用 MOQ 嵌套类和接口(interface) C# 进行单元测试

标签 c# unit-testing moq

嗨,我有以下接口(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/

相关文章:

java - 如何对没有参数的 void 方法进行单元测试

spring - 在 Spring 中测试从 Controller 调用 rest Controller

c# - 使用 Moq 将参数修改为 stub void 方法

c# - 浅拷贝值类型数组的一段

c# - 如何在 C# 中更改选项卡控件的字体属性而不更改其子控件的字体?

c# - 如何在 Visual Studio C# 项目中编译 hlsl 着色器文件

c# - Visual Studio 2015 - 无法实时编译和编辑并继续工作

java - 从 Java 到 Coldfusion 的多部分文件传输 - 无前导边界 : %PDF-1. 4

c# - 最小起订量:我可以验证一个 setter 只被调用了 N 次吗?

c# - 关于使用 Setup() 设置最小起订量行为的问题