【发布时间】:2026-02-15 16:50:01
【问题描述】:
假设: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:\\does\\not\\exist\\file.ext";
var mock = new Mock<MyFileType>(nonexistingPath);
}
测试失败,NUnit 报告从未抛出异常。
我确实找到了一个 section in the NUnit docs 谈论断言异常,但这些示例似乎不是我想要做的。我还在开始使用 NUnit 和 Moq,所以我可能会走错路。
更新:
为了帮助阐明为什么这个例子使用了一个抽象类,它是一系列文件类型的基类,其中只有数据的加载和处理在子类类型之间会有所不同。我最初的想法是将打开/设置的逻辑放入一个基类中,因为它对所有类型都是相同的。
【问题讨论】:
-
我不确定这是否与您的问题直接相关,但是将您的字符串定义更改为使用
@""语法更具可读性且不易出错。例如,您可以简单地输入String nonexistingPath = @"C:\does\not\exist\file.ext";,而不是String nonexistingPath = "C:\\does\\not\\exist\\file.ext"; -
感谢您的提示。我已合并更改。
标签: c# unit-testing tdd nunit moq