在 Nunit 3.0 及更高版本中测试异常

Testing Exceptions in Nunit 3.0 and above

我正在尝试测试异常,NUnit 3.11 给我错误,单元测试失败。如果 Nunit 收到此异常,我希望 Nunit 绿色通过,而不是出错。我该如何解决?

如果你愿意,可以随意改进代码,几个月前才开始学习编程。

当运行它给出异常本身,不通过。

测试错误 - 消息:System.ArgumentException:数据过多

public class ParseVendorSupply
{
    public VendorSupply FromCsv(string csvLine)
    {
        string[] values = csvLine.Split(',');
        if (values.Length > 3)
        {
            throw new System.ArgumentException("Too much data");
        }
        VendorSupply vendorsupply = new VendorSupply();
        vendorsupply.VendorId = Convert.ToInt16(values[0]);
        vendorsupply.ProductId = Convert.ToInt16(values[1]);
        vendorsupply.Quantity = Convert.ToInt16(values[2]);
        return vendorsupply;
    }
}

测试:

public class ParseVendorSupplyNunit
{

    ParseVendorSupply parseVendorSupplytest = new ParseVendorSupply();

    [Test]
    public void FromCsv_ParseCorrectly_Extradata()
    {
        string csvLineTest = "5,8,3,9,5";
        //VendorSupply vendorsupply = parseVendorSupplytest.FromCsv(csvLineTest);
        Assert.That(parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);
    }

Wrap 方法 您正在测试 Action

Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
Assert.That(parseFromCsv, Throws.ArgumentException)

并且在测试常见异常时,例如 ArgumentException,也始终测试异常消息。
因为在其他一些地方可能会发生常见的异常,并且测试会因为错误的原因而通过。

我更喜欢使用 FluentAssertions,我发现 little bid 更具可读性。

Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
parseFromCsv.Should().Throw<ArgumentException>().WithMessage("Too much data");

您需要将正在测试的方法作为 Action 传递。然后,您可以使用 Assert.Throws<> 方法:

Assert.Throws<ArgumentException>(() => parseVendorSupplytest.FromCsv(csvLineTest));

如果您使用 async/await

,还有一个 async 版本
Assert.ThrowsAsync<ArgumentException>(async () => await parseVendorSupplytest.FromCsv(csvLineTest));

建议使用 Action 的答案有效,但 NUnit 不需要 Action。我创建这个代码是因为我认为您了解为什么您现有的代码不起作用是很重要的。

问题是你的断言的第一个参数在调用断言之前调用了方法。你的 Assert.That 永远不会被调用,因为在评估参数时抛出了异常。

定义一个 Action 可以避免这个问题,因为它指定了一个不会立即进行的方法调用。

但是,在 NUnit 中指定它的更通俗的方法是直接使用 lambda...

Assert.That(() => parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);