gpt4 book ai didi

C# 如何使用 AutoFixture 简化单元测试字符串参数

转载 作者:太空狗 更新时间:2023-10-29 20:27:07 26 4
gpt4 key购买 nike

我正在尝试创建一种在单元测试中测试字符串参数的简单方法,对于大多数字符串参数,我想检查参数为 Null、Empty 或仅包含空格时的行为。

在大多数情况下,我使用 string.IsNullOrWhiteSpace() 检查参数,如果它具有这三个值之一,则抛出异常。

现在对于单元测试,似乎我必须为每个字符串参数编写三个单元测试。一种用于空值,一种用于空值,一种用于空白。

想象一个有 3 或 4 个字符串参数的方法,那么我需要编写 9 或 12 个单元测试......

谁能想出一个简单的方法来测试这个?也许使用 AutoFixture?

最佳答案

避免duplicating the same test您可以多次写 parameterized test .

如果你使用 xUnit,你会写一个所谓的 theory .理论意味着您正在证明一个原则,即当给定相同类型输入数据的不同样本时,某个函数的行为符合预期。例如:

[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void Should_throw_argument_exception_when_input_string_is_invalid(string input)
{
Assert.Throws<ArgumentException>(() => SystemUnderTest.SomeFunction(input));
}

xUnit 运行器将多次运行此测试,每次分配 input [InlineData] 中指定的值之一的参数属性。

如果被测试的函数有多个参数,您可能不关心传递给其余参数的值,只要其中至少一个是 null 的字符串即可。 , 空或仅包含空格。

在这种情况下,您可以将参数化测试与 AutoFixture 结合使用。 AutoFixture 旨在为您提供 general-purpose test data当您不一定关心确切值是什么时,这足以在大多数情况下使用。

为了将它与 xUnit 理论一起使用,您需要添加 AutoFixture.Xunit NuGet 包(或 AutoFixture.Xunit2 取决于您使用的版本)到您的测试项目并使用 InlineAutoData属性:
[Theory]
[InlineAutoData(null)]
[InlineAutoData("")]
[InlineAutoData(" ")]
public void Should_throw_argument_exception_when_the_first_input_string_is_invalid(
string input1,
string input2,
string input3)
{
Assert.Throws<ArgumentException>(() =>
SystemUnderTest.SomeFunction(input1, input2, input3));
}

只有 input1参数将有一个特定的值,而其余的将由 AutoFixture 分配随机字符串。

这里要注意的一件事是通过 [InlineAutoData] 传递的值。属性根据它们的位置分配给测试参数。由于我们需要分别测试所有三个参数的相同行为,因此我们必须编写三个测试:
[Theory]
[InlineAutoData(null)]
[InlineAutoData("")]
[InlineAutoData(" ")]
public void Should_throw_argument_exception_when_the_second_input_string_is_invalid(
string input2,
string input1,
string input3)
{
Assert.Throws<ArgumentException>(() =>
SystemUnderTest.SomeFunction(input1, input2, input3));
}

[Theory]
[InlineAutoData(null)]
[InlineAutoData("")]
[InlineAutoData(" ")]
public void Should_throw_argument_exception_when_the_third_input_string_is_invalid(
string input3,
string input1,
string input2)
{
Assert.Throws<ArgumentException>(() =>
SystemUnderTest.SomeFunction(input1, input2, input3));
}

关于基于属性的测试

我不禁认为这些类型的测试场景非常适合基于属性的测试。在不涉及太多细节的情况下,基于属性的测试是通过使用生成的输入多次运行函数来证明函数的特定行为(或“属性”)。

In other words :

Property-based tests make statements about the output of your code based on the input, and these statements are verified for many different possible inputs.



在您的情况下,您可以编写一个测试来验证该函数是否抛出 ArgumentException只要其中至少一个参数是 null 、空字符串或仅包含空格的字符串。

在 .NET 中,您可以使用名为 FsCheck 的库。编写和执行基于属性的测试。虽然 API 主要设计为在 F# 中使用,但它也可以在 C# 中使用。

但是,在这种特殊情况下,我认为您最好坚持使用常规参数化测试和 AutoFixture 来实现相同的目标。事实上,使用 FsCheck 和 C# 编写这些测试最终会变得更加冗长,并且在健壮性方面不会真正为您买单。

更新:AutoFixture.Idioms

正如@RubenBartelink 指出的那样 in the comments ,还有一个选择。 AutoFixture 将常见的断言封装在一个名为 AutoFixture.Idioms 的小型库中。 .您可以使用它来集中对 string 的期望。参数由方法验证并在您的测试中使用它们。

虽然我有 my reservations在这种方法中,为了完整起见,我将在此处添加它作为另一种可能的解决方案:
[Theory, AutoData]
public void Should_throw_argument_exception_when_the_input_strings_are_invalid(
ValidatesTheStringArguments assertion)
{
var sut = typeof(SystemUnderTest).GetMethod("SomeMethod");

assertion.Verify(sut);
}

public class ValidatesTheStringArguments : GuardClauseAssertion
{
public ValidatesTheStringArguments(ISpecimenBuilder builder)
: base(
builder,
new CompositeBehaviorExpectation(
new NullReferenceBehaviorExpectation(),
new EmptyStringBehaviorExpectation(),
new WhitespaceOnlyStringBehaviorExpectation()))
{
}
}

public class EmptyStringBehaviorExpectation : IBehaviorExpectation
{
public void Verify(IGuardClauseCommand command)
{
if (!command.RequestedType.IsClass
&& !command.RequestedType.IsInterface)
{
return;
}

try
{
command.Execute(string.Empty);
}
catch (ArgumentException)
{
return;
}
catch (Exception e)
{
throw command.CreateException("empty", e);
}

throw command.CreateException("empty");
}
}

public class WhitespaceOnlyStringBehaviorExpectation : IBehaviorExpectation
{
public void Verify(IGuardClauseCommand command)
{
if (!command.RequestedType.IsClass
&& !command.RequestedType.IsInterface)
{
return;
}

try
{
command.Execute(" ");
}
catch (ArgumentException)
{
return;
}
catch (Exception e)
{
throw command.CreateException("whitespace", e);
}

throw command.CreateException("whitespace");
}
}

基于 NullReferenceBehaviorExpectation 中表达的期望, EmptyStringBehaviorExpectation , 和 WhitespaceOnlyStringBehaviorExpectation AutoFixture 将自动尝试调用名为 "SomeMethod" 的方法。与 null , 分别为空字符串和空格。

如果该方法没有抛出正确的异常——如 catch 中所述阻止在期望类中——然后 AutoFixture 本身会抛出一个异常来解释发生了什么。下面是一个例子:

An attempt was made to assign the value whitespace to the parameter "p1" of the method "SomeMethod", and no Guard Clause prevented this. Are you missing a Guard Clause?



您还可以通过简单地自己实例化对象来使用没有参数化测试的 AutoFixture.Idioms:
[Fact]
public void Should_throw_argument_exception_when_the_input_strings_are_invalid()
{
var assertion = new ValidatesTheStringArguments(new Fixture());
var sut = typeof(SystemUnderTest).GetMethod("SomeMethod");

assertion.Verify(sut);
}

关于C# 如何使用 AutoFixture 简化单元测试字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34284527/

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