C# 具有RelayCommand的单元测试视图模型
我的视图模型单元测试有问题。我想这样测试我的代码:C# 具有RelayCommand的单元测试视图模型,c#,.net,nunit,mvvm-light,C#,.net,Nunit,Mvvm Light,我的视图模型单元测试有问题。我想这样测试我的代码: [Test] public void SelectCommand_ExecutedWithNull_Throws() { // * Arrange var fixture = new Fixture(); var sut = fixture.Build(); // * Act & Assert Assert.Throws<ArgumentNullException>(() =>
[Test]
public void SelectCommand_ExecutedWithNull_Throws()
{
// * Arrange
var fixture = new Fixture();
var sut = fixture.Build();
// * Act & Assert
Assert.Throws<ArgumentNullException>(() => sut.SelectCommand.Execute(null));
}
如何连接命令:
private async void Select(IInsuranceCh insurance)
{
if (insurance == null)
throw new ArgumentNullException("insurance");
try
{
/* ... */
}
catch (Exception err)
{
_childWindowService.ShowLoadingErrorWindow(err);
}
finally
{
IsBusy = false;
}
}
SelectCommand = new RelayCommand<IInsuranceCh>(Select);
然而,当我尝试这样做时,测试失败了,即使异常被抛出并且没有在我的代码中捕获。当我尝试捕获sut.SelectCommand.Executenull时;语句,则未输入catch块。这让我相信,MVVM Light Toolkit中的RelayCommand正在吞噬异常。我怎样才能防止呢
编辑:一些澄清&Assert.Throws
EDIT2:发布操作和命令连接。可能异步起了作用?原因是:RelayCommand正在使用反射来调用动态方法。反射将动作的异常包装为内部异常
When created, the TargetInvocationException is passed a reference to the exception thrown by the method invoked through reflection. The InnerException property holds the underlying exception.
https://msdn.microsoft.com/en-us/library/system.reflection.targetinvocationexception(v=vs.110).aspx
如果要从外部库捕获异常。您必须在调试器的选项中禁用“仅我的代码” 不是问题的答案,但不要使用ExpectedException属性。而是使用Assert.Throws或Assert.Thatcode、Throws.ArgumentNullException。因为使用ExpectedException的测试可能是假阳性。即使你的夹具设置阶段引发异常而不是act阶段,它也可以通过测试。你是使用你的RelayCommand还是来自第三方?@Neil是的,我使用的是来自MVVM Light的RelayCommand。@SriramSakthivel OK,但结果是一样的。实际上,我想引发异常。我想测试代码中的ArgumentNull异常是否被抛出。有趣的是,我的代码实际上被执行了。并使用调试器测试抛出的异常。但这个例外被吞没了。不过,我在MVVM Light的源代码中没有看到任何try-catch。这就是我感到困惑的原因。相关的消息来源是:明白。如果操作中出现错误,命令将引发异常。请参阅我的test var command=new RelayCommand p=>{if p==null{throw new ArgumentNullException;}},p=>true;Assert.Throws=>command.Executenull;你能发布你的行动吗?我添加了代码。也许问题是我的方法是异步的?我想是的,你确定你的操作是完全执行的吗?