【发布时间】:2017-08-01 10:39:15
【问题描述】:
我是 TDD 开发的新手,刚刚开始使用 Nunit 3.7.1、C# 和 .NET Framework 4.7 进行一些测试。
我有这个测试类:
[TestFixture]
class ProcessTrzlExportTest
{
private ImportTrzlBatch _import;
[SetUp]
public void SetUpImportTrzlBatch()
{
_import = new ImportTrzlBatch();
}
[Test]
public void ShouldThrowArgumentExceptionWithNullPath()
{
// Arrange
string path = null;
// Act
ActualValueDelegate<object> testDelegate = () => _import.LoadBatchFile(path);
// Assert
Assert.That(testDelegate, Throws.TypeOf<ArgumentNullException>());
}
[Test]
public void ShouldThrowArgumentExceptionWithEmptyPath()
{
string path = string.Empty;
// Act
ActualValueDelegate<object> testDelegate = () => _import.LoadBatchFile(path);
// Assert
Assert.That(testDelegate, Throws.TypeOf<ArgumentNullException>());
}
[Test]
public void ShouldThrowArgumentExceptionWithWhiteSpacesPath()
{
string path = " ";
// Act
ActualValueDelegate<object> testDelegate = () => _import.LoadBatchFile(path);
// Assert
Assert.That(testDelegate, Throws.TypeOf<ArgumentNullException>());
}
}
要测试这个类:
public class ImportTrzlBatch
{
public object LoadBatchFile(string path)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentNullException(nameof(path));
return null;
}
}
我正在测试path 不为空、空或空白。我有三种测试方法可以用三种不同的输入来测试同一种方法。
我可以使用私有测试方法不重复代码并从这三个不同路径的三个方法中调用它吗?
另一个问题是我正在使用这个:ActualValueDelegate<object> testDelegate = () => _import.LoadBatchFile(path);
测试是否抛出ArgumentNullException。
是否有另一种方法可以在不使用委托的情况下测试是否抛出异常?
顺便说一句,我已经复制了代码以检查它是否从这个 SO 答案中抛出 ArgumentNullException:https://stackoverflow.com/a/33897450/68571
【问题讨论】:
-
你的意思是使用
Assert.Throws<>()还是Assert.DoesNotThrow<>()? -
我不知道。我已经从这个 SO 答案中复制了
Assert.That:stackoverflow.com/a/33897450/68571 -
你不应该在同一篇文章中问两个问题。
标签: c# unit-testing nunit