c# – 从模拟对象构造函数中抛出异常
发布时间:2020-12-15 04:21:23 所属栏目:百科 来源:网络整理
导读:假设:VS2010,.NET 4,C#,NUnit,Moq 我是TDD的新人,在通过项目工作时遇到这个问题. 给定类: public abstract class MyFileType{ public MyFileType(String fullPathToFile) { if (!File.Exists(fullPathToFile)) { throw new FileNotFoundException(); } //
假设:VS2010,.NET 4,C#,NUnit,Moq
我是TDD的新人,在通过项目工作时遇到这个问题. 给定类: public abstract class MyFileType { public MyFileType(String fullPathToFile) { if (!File.Exists(fullPathToFile)) { throw new FileNotFoundException(); } // method continues } } 我试图使用以下方法进行测试: [Test] [ExpectedException(typeof(System.IO.FileNotFoundException))] public void MyFileType_CreationWithNonexistingPath_ExceptionThrown() { String nonexistingPath = "C:doesnotexistfile.ext"; var mock = new Mock<MyFileType>(nonexistingPath); } 测试失败,NUnit报告的异常从未被抛出. 我确实发现一个section in the NUnit docs谈论断言与例外,但这些例子似乎并不像我想要做的.我仍然开始使用NUnit和Moq,所以我可能会这样做错了. 更新: 为了帮助澄清为什么这个例子使用抽象类,它是一个系列文件类型的基类,只有数据的加载和处理在子类型之间不同.我最初的想法是将open / setup的逻辑放在一个基类中,因为它对于所有类型都是相同的. 解决方法
如果你必须让这个类是抽象的,那么我们应该只是实现它,因为它是(简单):
MSDN: an abstract class 所以,同意(与alexanderb),这里可能不需要一个模拟,还有Stecy在.Throws NUnit Assert扩展,你可以在测试中创建一个类,调用基类如下: using System; using System.IO; namespace fileFotFoundException { public abstract class MyFile { protected MyFile(String fullPathToFile) { if (!File.Exists(fullPathToFile)) throw new FileNotFoundException(); } } } namespace fileFotFoundExceptionTests { using fileFotFoundException; using NUnit.Framework; public class SubClass : MyFile { public SubClass(String fullPathToFile) : base(fullPathToFile) { // If we have to have it as an abstract class... } } [TestFixture] public class MyFileTests { [Test] public void MyFile_CreationWithNonexistingPath_ExceptionThrown() { const string nonExistingPath = "C:doesnotexistfile.ext"; Assert.Throws<FileNotFoundException>(() => new SubClass(nonExistingPath)); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |