模拟IIndex <tkey,tvalue =“”> </tkey,>

时间:2014-04-08 14:10:29

标签: 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));
}

1 个答案:

答案 0 :(得分:4)

所以我重新创建了类似于你的设置的东西

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>