gpt4 book ai didi

c# - MSTest 单元测试断言特定的异常消息

转载 作者:行者123 更新时间:2023-12-03 08:45:57 25 4
gpt4 key购买 nike

我正在为非常小的项目编写我的第一个单元测试。这里预期结果和结果都返回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)>.

最佳答案

看看这个;

var expectedExcetpion = new ArgumentNullException();
// Act & Assert
var result = Assert.ThrowsException<ArgumentNullException>(() => generateFile.InsertFileBeginning(parameter));
Assert.AreEqual(expectedExcetpion, result);

expectedException 是一个 ArgumentNullException 类型的对象,result 也是一个 ArgumentNullException 类型的对象 - 但它们不是同一个对象!您有 2 个相同类型的实例。

现在 AreEqual(..) 使用我在网上收集到的 .Equals

我认为您正在将 ExpectedException 的引用与此处的结果进行比较。它们当然不一样。您应该做的(如果我的假设是正确的)是检查结果是否具有相同类型,而不是使用 AreEqual(..)

看来你可以使用这个方法:Assert.IsInstanceOfType https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.assert.isinstanceoftype?view=mstest-net-1.2.0

例如:

Assert.IsInstanceOfType(result, typeof(ArgumentNullException));

关于c# - MSTest 单元测试断言特定的异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61476060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com