我是TDD開發新手,剛開始使用Nunit 3.7.1,C#和.NET Framework 4.7進行一些測試。使用私人nunit測試不要重複我自己
我有這個測試類:
[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
。
是否有另一種方法來測試是否拋出異常而不使用委託?
順便說一句,我抄代碼來檢查它是否拋出ArgumentNullException
從這個蘇答案:https://stackoverflow.com/a/33897450/68571
你的意思是使用'Assert.Throws <>()'或'Assert.DoesNotThrow <>()'? – kayess
我不知道。我已經從這個SO複製了'Assert.That'回答:https://stackoverflow.com/a/33897450/68571 – VansFannel
你不應該在同一篇文章中提出兩個問題。 –