我使用 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]为空。有人有解决我的问题的方法吗?一个解决方案可能是在测试之前启动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));
}