我有一个应用程序,我在一个类的构造函数中抛出异常。我用nUnit编写了单元测试和集成测试,并检查是否在需要时抛出此异常,例如:
Assert.That(() => _fileOperationsModel.OpenFile("abc"), Throws.Exception.TypeOf<MissingFieldException>());
并且在我开始使用Autofac之前,它一直很好。我需要创建一个使用autofac引发异常的类,因此在调用构造函数并引发异常时,不再存在MissingFieldException
,而是Autofac.Core.DependencyResolutionException
。
并且在该例外的细节中,有4个内部例外。其中3个也是DependencyResolutionException
,最后一个是我的MissingFieldException
。
我正在尝试像这样测试它:
var ex = Assert.Throws<Autofac.Core.DependencyResolutionException>(() => _fileOperationsModel.OpenFile("abc"));
Assert.That(ex.InnerException, Is.TypeOf<MissingFieldException>());
但是它不起作用,因为InnerException
只是一个,它也是DependencyResolutionException
。
您是否知道如何处理此异常以及如何对其进行测试?我是Autofac的新手,我一直在尝试寻找有关的内容,但没有结果。
编辑:我知道我可以这样做
var ex = Assert.Throws<Autofac.Core.DependencyResolutionException>(() => _fileOperationsModel.OpenFile("abc"));
Assert.That(ex.InnerException, Is.TypeOf<DependencyResolutionException>());
Assert.That(ex.InnerException.InnerException, Is.TypeOf<DependencyResolutionException>());
Assert.That(ex.InnerException.InnerException.InnerException, Is.TypeOf<DependencyResolutionException>());
Assert.That(ex.InnerException.InnerException.InnerException.InnerException, Is.TypeOf<MissingFieldException>());
但是也许有更好的解决方案而不是那么糟糕的解决方案?
也许this earlier可以给您一些启发。
否则,您可以尝试根据constraint matcher编写自己的the default exception matcher,但是,在第50行中遍历内部异常。
如果两者都不是您的选择,则可以采用您自己的建议解决方案。我不认为目前在NUnit中实现深层嵌套内部异常验证。而且,我认为您可以在不验证中间体DependencyResolutionExceptions
的情况下进行操作。