1

我试图掌握要测试的内容和不测试的内容。

鉴于这个非常简单的实用程序类:

public static class Enforce
{
    public static void ArgumentNotNull<T>(T argument, string name)
    {
        if (name == null)
            throw new ArgumentNullException("name");

        if (argument == null)
            throw new ArgumentNullException(name);
    }
}

你会说以下测试就足够了吗?或者我是否还需要测试有效参数实际上不抛出的相反条件?

[Fact]
    public void ArgumentNotNull_ShouldThrow_WhenNameIsNull()
    {
        string arg = "arg";
        Action a = () => Enforce.ArgumentNotNull(arg, null);

        a.ShouldThrow<ArgumentNullException>();
    }

    [Fact]
    public void ArgumentNotNull_ShouldThrow_WhenArgumentIsNull()
    {
        string arg = null;
        Action a = () => Enforce.ArgumentNotNull(arg, "arg");

        a.ShouldThrow<ArgumentNullException>();
    }

您是否需要测试一般的反向条件?或者在这种情况下可以安全地假设吗?

请注意,我使用的是 xUnit 和 FluentAssertions。

4

1 回答 1

1

单元测试的重点是测试您编写的代码。鉴于 ArgumentNullException 是您使用的 API 的一部分,测试其行为是否符合您的期望是测试 API 而不是您的代码,只会使水变得浑浊。

单元测试可以测试您为您编写的代码编写的方法的所有行为,因此就足够了。

于 2013-08-14T18:57:55.967 回答