我正在测试模型存储库以查看它是否调用了消息总线。我不确定这是否是一个很好的测试,但这是我的想法:我通常将bus.send放入控制器(这是一个MVC网络应用程序),但因为我不想专门测试我的控制器逻辑,我把它移到了存储库中。在我的情况下,控制器很简单。存储库使用总线和模型数据库来构建视图模型。
无论如何,这个问题的关键是我正在运行的moq测试。我嘲笑了总线并希望验证它是从存储库调用的。
测试如下:
public class when_creating_new_clinic
{
Establish context = () =>
{
clinicID = Guid.NewGuid();
model = new ClinicModel
{
ClinicID = clinicID,
Alias = "alias",
Title = "title"
// stuff omitted
};
newClinicData = new NewClinicData
{
ClinicID = clinicID,
Alias = "alias",
Title = "title"
// stuff omitted
};
cmd = new CreateClinicCmd(newClinicData);
bus = new Mock<IMessageBusAgent>();
repository = new ClinicModelRepository(bus.Object);
bus.Setup(b => b.Send(cmd));
};
Because it = () => repository.Create(model);
It should_send_create_clinic_command_to_bus = () =>
{
bus.Verify(b => b.Send(cmd), Times.Exactly(1));
};
static ClinicModelRepository repository;
static ClinicModel model;
static Mock<IMessageBusAgent> bus;
static NewClinicData newClinicData;
static Guid clinicID;
static CreateClinicCmd cmd;
}
存储库的要点是:
public class ClinicModelRepository : IClinicModelRepository
{
private readonly IMessageBusAgent m_bus;
public ClinicModelRepository(IMessageBusAgent bus)
: this()
{
m_bus = bus;
}
public void Create(ClinicModel clinicModel)
{
// stuff omitted (data is mapped from clinicModel)
m_bus.Send(new CreateClinicCmd(data));
}
}
IMessageBusAgent声明为:
public interface IMessageBusAgent : IDomainCommandSender, IDomainEventPublisher, IUnitOfWork
{
}
测试结果如下:
when creating new clinic
»应该将create clinic命令发送到总线(FAIL)
测试'应该向公交车发送创建诊所命令'失败: Moq.MockException: 模拟上的预期调用恰好是1次,但是是0次:b =&gt; b.Send(when_creating_new_clinic.cmd)
Configured setups:
b => b.Send<CreateClinicCmd>(when_creating_new_clinic.cmd), Times.Never
Performed invocations:
IDomainCommandSender.Send(ArReg.Commands.CreateClinicCmd)
IUnitOfWork.Commit()
at Moq.Mock.ThrowVerifyException(MethodCall expected, IEnumerable`1 setups, IEnumerable`1 actualCalls, Expression expression, Times times, Int32 callCount)
at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times)
at Moq.Mock.Verify[T](Mock mock, Expression`1 expression, Times times, String failMessage)
at Moq.Mock`1.Verify(Expression`1 expression, Times times)
Repositories\when_creating_new_clinic.cs(51,0): at ArReg.Tests.Specs.Repositories.when_creating_new_clinic.<.ctor>b__4()
at Machine.Specifications.Model.Specification.InvokeSpecificationField()
at Machine.Specifications.Model.Specification.Verify()
0通过,1次失败,0次跳过,耗时3.58秒(Machine.Specifications 0.4.24-f7fb6b5)。
在IDomainCommandSender中声明了Send()命令,那么我该如何设置测试以便验证正确的呼叫?
由于
答案 0 :(得分:3)
您的总线设置有一点错误。它应该是这样的:
bus.Setup(b => b.Send(It.IsAny<CreateClinicCmd>()));
原因:您使用上面创建的两个代码行的CreateClinicCmd
实例编写了您的设置。在您的测试类ClinicModelRepository
中,您创建该类的另一个实例并调用您的总线模拟。此调用与您在设置中编写的调用不匹配。