我測試的模型庫,看它是否調用消息總線。我不知道,如果這是在所有的一個很好的測試,但這裏是我的想法:我通常會把bus.send到控制器(這是一個MVC Web應用程序),但因爲我不想要測試我的控制器專爲邏輯,我把它移入存儲庫。控制器在我的情況下很簡單。存儲庫使用總線和模型數據庫來構建視圖模型。我該如何聲明一個方法被moq和mspec這個嘲弄的依賴關係調用?
不管怎麼說,這個問題的關鍵是起訂量測試我運行。我嘲笑公共汽車,並想驗證它是從庫中調用的。
測試看起來是這樣的:
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
»應該發送創建診所命令總線(FAIL)
測試‘應該發送創建診所命令總線’失敗: Moq.MockException:在模擬 預期調用正好是1倍,但0次:b => 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)。
在send()命令在IDomainCommandSender宣佈讓我怎麼需要安裝測試,這樣我可以驗證正確的電話嗎?
謝謝
不知道從哪裏在這種情況下開始。調用總線發送命令的存儲庫...真的嗎?您可能需要重新閱讀基礎知識。 –
它不是一個域存儲庫;代碼片段來自不完整的實現。事件源/域側尚未實現;現在命令處理程序正在寫入讀取方。不要關注存儲庫。 –