【发布时间】:2019-04-29 17:27:34
【问题描述】:
我第一次尝试在 WPF 应用程序中进行模拟。我正在测试的代码是 MVVM ViewModel 方法的一部分,如下所示:
try
{
var airframesForRegistration = this.UnitOfWork.Airframes.GetAirframesForRegistration(this.SearchRegistration);
this.currentAirframes = new ObservableCollection<Airframe>(airframesForRegistration);
}
catch (Exception ex)
{
this.logger.Error($"Could not access the database", ex);
throw;
}
我想测试一下
- 错误被写入记录器服务和
- 抛出异常。
为此,我使用 XUnit 和 Moq:
[Fact]
public void GetAirframesForSearchRegistration_DBAccessFail()
{
using (var mock = AutoMock.GetLoose())
{
mock.Mock<IUnitOfWork>()
.Setup(x => x.Airframes.GetAirframesForRegistration("AAAA"))
.Throws(new DataException());
string message = "Could not access the database";
DataException exception = new DataException();
mock.Mock<ILog>()
.Setup(x => x.Error(message, exception));
var afrvm = mock.Create<AirframesForRegistrationViewModel>();
afrvm.SearchRegistration = "AAAA";
Assert.Throws<DataException>(() => afrvm.GetAirframesForSearchRegistration());
mock.Mock<ILog>()
.Verify(x => x.Error(message, exception), Times.Exactly(1));
}
因此测试失败:
Message: Moq.MockException :
Expected invocation on the mock exactly 1 times, but was 0 times: x => x.Error("Could not access the database'", System.Data.DataException: Data Exception.)
Configured setups:
ILog x => x.Error("Could not access the database", System.Data.DataException: Data Exception.)
Performed invocations:
ILog.Warn("No Operators found in the database")
ILog.Warn("No airframe statuses found in the database")
ILog.Error("Could not access the database", System.Data.DataException: Data Exception.
at Moq.MethodCall.Execute(Invocation invocation) in C:\projects\moq4\src\Moq\MethodCall.cs:line 120
(注意,额外的 ILog 警告出现在 ViewModel 的其他地方,我期待这些警告)。
问题
这意味着错误日志被调用了,但是测试失败了,因为它被调用了零次!如何设置 Moq 和 XUnit 以正确测试此场景?
【问题讨论】:
-
记录器参数的设置是问题所在。不同的实例意味着它们不会匹配
-
@Nkosi 我没有通过在 .Setup 和 .Verify 中使用变量“消息”和“异常”来确保使用相同的实例吗?
-
模拟工作单元抛出一个新异常。不是你所期待的。
标签: wpf exception logging moq xunit