【发布时间】:2020-04-28 08:42:13
【问题描述】:
我正在为非常小的项目编写我的第一个单元测试。这里预期的结果和结果都返回 ArgumentNullException 但测试仍然失败。知道为什么吗?
[TestMethod]
public void InsertFileBeginning_FilePathNull_ReturnArgumentNullException()
{
// Arrange
var generateFile = new GenerateFile();
string parameter = null; //pass FilePath Null
var expectedExcetpion = new ArgumentNullException();
// Act & Assert
var result = Assert.ThrowsException<ArgumentNullException>(() => generateFile.InsertFileBeginning(parameter));
Assert.AreEqual(expectedExcetpion, result);
}
--------InsertFileBeginning 函数--------
public void InsertFileBeginning(string filePath)
{
try
{
using (var fs = new FileStream(filePath, FileMode.Create))
{
Byte[] metadata = new UTF8Encoding(true).GetBytes("THis is a test content");
fs.Write(metadata, 0, metadata.Length);
}
}
catch (Exception exception)
{
throw exception;
}
}
错误:
预期:System.ArgumentNullException:值不能为空。
实际:System.ArgumentNullException:路径不能为空。参数名称:路径
Message: Assert.AreEqual failed. Expected:<System.ArgumentNullException: Value cannot be null.>. Actual:<System.ArgumentNullException: Path cannot be null.
Parameter name: path
at SmartTestSelecter.GenerateFile.InsertFileBeginning(String filePath) in C:\Users\CC\SmartTestSelecter\GenerateFile.cs:line 31
at SmartTestSelecterUnitTests.GenerateFileTest.<>c__DisplayClass0_0.<InsertFileBeginning_FilePathNull_ReturnArgumentNullException>b__0() in C:\Users\CC\STSUnitTests\GenerateFileTest.cs:line 21
at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsException[T](Action action, String message, Object[] parameters)>.
【问题讨论】:
-
请分享
InsertFileBeginning方法的样子 -
请看一下这个帖子,它可能对你的情况有帮助unit testing for ArgumentNullException by param name
-
@PavelAnikhouski 非常感谢,是的,这个解决方法确实可以比较参数名称。
标签: c# unit-testing exception mstest argumentnullexception