首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嘲弄IIndex<TKey,TValue>

嘲弄IIndex<TKey,TValue>
EN

Stack Overflow用户
提问于 2014-04-08 14:10:28
回答 1查看 2.4K关注 0票数 7

我用IIndex作为工厂来决定使用哪种服务。当我试图对我的CommunicationJob类进行单元测试时,我正在与IIndex的模拟进行斗争。

代码语言:javascript
复制
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);
        }
    }
}

问题是这是_csn.GetType().Name null。有人能解决我的问题吗?一个解决方案可能是在测试之前启动Autofac,但我不知道如何在测试上下文中加载AutoFac。

我的测试看起来如下:

代码语言:javascript
复制
[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));
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-08 14:21:32

所以我重新创建了一些类似于你的设置

代码语言:javascript
复制
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):

代码语言:javascript
复制
// 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>

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22939622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档