c# - 模拟 IIndex<TKey, TValue>

标签 c# unit-testing moq autofac

我使用 IIndex 作为工厂来决定要使用的服务。当我尝试对我的 CommunicationJob 类进行单元测试时,我正在为 IIndex 的模拟而苦苦挣扎。

public class CommunicationJob : BaseJob
{
    private readonly IRepo<Notification> _nr;
    private readonly IIndex<string, IService> _cs;

    public CommunicationJob
    (
        IRepo<Notification> nr,
        IIndex<string, IService> cs
    )
    {
        _nr= nr;
        _cs= cs;
    }

    public void Do(DateTime date)
    {
        foreach (var n in _nr.GetList())
        {
            _cs[n.GetType().Name].Send(n);

            nr.Sent = DateTime.Now;
            nr.Update(n, true);
        }
    }
}

问题是 _cs[n.GetType().Name] 为 null。 有人能解决我的问题吗?一种解决方案是在测试前启动 Autofac,但我不知道如何在测试上下文中加载 AutoFac。

我的测试是这样的:

[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void WithNotifications(int numberOfNotifications)
{
    var fixture = new TestCommunicationJobFixture();

    var sut = fixture.WithNotifications(numberOfNotifications).GetSut();
    sut.Do(new DateTime());

    fixture.MockCommunicationService.Verify(x => x["EmailNotification"].Send(It.Is<Notification>(z => z.Sent != null)), Times.Exactly(numberOfNotifications));
    fixture.MockNotificationRepo.Verify(x => x.Update(It.Is<Notification>(z => z.Sent != null), true), Times.Exactly(numberOfNotifications));
}

最佳答案

所以我重新创建了与您的设置类似的东西

public class Something
{
    private readonly IIndex<string, IService> index;
    public Something(IIndex<string, IService> index)
    {
        this.index = index;
    }

    public void DoStuff()
    {
        this.index["someString"].Send();
    }
}

public interface IIndex<TKey, TValue>
{
    TValue this[TKey index] {get;set;}
}

public interface IService
{
    void Send();
}

然后像这样测试(使用 Moq):

// Arrange
var serviceMock = new Mock<IService>();

var indexMock = new Mock<IIndex<string, IService>>();
indexMock.Setup(x => x[It.IsAny<string>()]).Returns(serviceMock.Object);

var something = new Something(indexMock.Object);

// Act
something.DoStuff();

// Assert
serviceMock.Verify(x => x.Send());

希望这会为您指明正确的方向。显然你需要模拟你的 IRepo<Notification> .

关于c# - 模拟 IIndex<TKey, TValue>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22939622/

相关文章:

c# - 在 C# 中将委托(delegate)转换为通用委托(delegate)

c# - HttpClient 请求 ssl 网站,但无法在 uwp 中获取 cookie

java - 如何从 Spring Rest 文档中排除一些测试?

c# - 如何处理 Telerik RadGrid 中的空值(在列中)? (替换为 HTML)

c# - 存储库模式

javascript - 无法让 Jasmine 测试成功调用注入(inject)的服务

.net - 您如何指示 NUnit 从特定目录加载程序集的 dll.config 文件?

c# - 模拟存储过程的输出参数

c# - 如何使用已作为 IQurable 查询的 ToListAsync 变量来 Moq 设置等待?

c# - Moq 设置 当模拟实现具有相同方法签名的多个接口(interface)的接口(interface)时出现 InvalidCastException