C# 如何使用 AutoFixture 简化单元测试字符串参数
C# How to simplify unit testing string parameters using AutoFixture
我正在尝试创建一种在单元测试中测试字符串参数的简单方法,对于大多数字符串参数,我想检查参数为 Null、空或仅包含空格时的行为。
在大多数情况下,我使用 string.IsNullOrWhiteSpace() 检查参数,如果它具有这三个值之一则抛出异常。
现在进行单元测试,看来我必须为每个字符串参数编写三个单元测试。一种用于空值,一种用于空值,一种用于空格。
假设一个方法有 3 个或 4 个字符串参数,那么我需要编写 9 或 12 个单元测试...
谁能想出一个简单的方法来测试这个?也许使用 AutoFixture?
避免duplicating the same test multiple times you can write a 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 运行ner 将运行此测试多次,每次将input
参数分配给指定的值之一在 [InlineData]
属性中。
如果被测试的函数有多个参数,您可能不关心传递给其余参数的值是什么,只要其中至少一个是 null
、空或仅包含空格。
在这种情况下,您可以将参数化测试与 AutoFixture 相结合。 AutoFixture 旨在为您提供 general-purpose test data 足以在您不一定关心确切值是什么的大多数情况下使用。
为了将它与 xUnit 理论一起使用,您需要将 AutoFixture.Xunit NuGet package (or 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));
}
关于基于 属性 的测试的一句话
我不禁认为这些测试场景非常适合基于 属性 的测试。无需赘述,基于 属性 的测试是关于 通过 运行 证明函数的特定行为(或 "property") 多次生成输入。
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.
在您的情况下,您可以编写一个测试来验证只要至少一个参数是 null
、空字符串或仅包含一个字符串,函数就会抛出 ArgumentException
包含空格。
在 .NET 中,您可以使用名为 FsCheck 的库来编写和执行基于 属性 的测试。虽然 API 主要设计用于 F#,但它也可以用于 C#。
但是,在这种特殊情况下,我认为您最好坚持使用常规 参数化测试 和 AutoFixture 来实现相同的目标。事实上,使用 FsCheck 和 C# 编写这些测试最终会变得 更冗长 并且在稳健性方面不会给你带来太多好处。
更新:AutoFixture.Idioms
正如@RubenBartelink 指出的那样, there is another option. AutoFixture encapsulates common assertions in a small library called AutoFixture.Idioms。您可以使用它来集中对 string
参数如何通过方法验证的期望,并在您的测试中使用它们。
虽然我确实有 这种方法,但为了完整起见,我将把它添加到这里作为另一种可能的解决方案:
[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 将自动尝试使用 null
调用名为 "SomeMethod"
的方法,分别为空字符串和空格。
如果该方法没有抛出正确的异常——正如在期望 类 中的 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);
}
我正在尝试创建一种在单元测试中测试字符串参数的简单方法,对于大多数字符串参数,我想检查参数为 Null、空或仅包含空格时的行为。
在大多数情况下,我使用 string.IsNullOrWhiteSpace() 检查参数,如果它具有这三个值之一则抛出异常。
现在进行单元测试,看来我必须为每个字符串参数编写三个单元测试。一种用于空值,一种用于空值,一种用于空格。
假设一个方法有 3 个或 4 个字符串参数,那么我需要编写 9 或 12 个单元测试...
谁能想出一个简单的方法来测试这个?也许使用 AutoFixture?
避免duplicating the same test multiple times you can write a 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 运行ner 将运行此测试多次,每次将input
参数分配给指定的值之一在 [InlineData]
属性中。
如果被测试的函数有多个参数,您可能不关心传递给其余参数的值是什么,只要其中至少一个是 null
、空或仅包含空格。
在这种情况下,您可以将参数化测试与 AutoFixture 相结合。 AutoFixture 旨在为您提供 general-purpose test data 足以在您不一定关心确切值是什么的大多数情况下使用。
为了将它与 xUnit 理论一起使用,您需要将 AutoFixture.Xunit NuGet package (or 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));
}
关于基于 属性 的测试的一句话
我不禁认为这些测试场景非常适合基于 属性 的测试。无需赘述,基于 属性 的测试是关于 通过 运行 证明函数的特定行为(或 "property") 多次生成输入。
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.
在您的情况下,您可以编写一个测试来验证只要至少一个参数是 null
、空字符串或仅包含一个字符串,函数就会抛出 ArgumentException
包含空格。
在 .NET 中,您可以使用名为 FsCheck 的库来编写和执行基于 属性 的测试。虽然 API 主要设计用于 F#,但它也可以用于 C#。
但是,在这种特殊情况下,我认为您最好坚持使用常规 参数化测试 和 AutoFixture 来实现相同的目标。事实上,使用 FsCheck 和 C# 编写这些测试最终会变得 更冗长 并且在稳健性方面不会给你带来太多好处。
更新:AutoFixture.Idioms
正如@RubenBartelink 指出的那样string
参数如何通过方法验证的期望,并在您的测试中使用它们。
虽然我确实有
[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 将自动尝试使用 null
调用名为 "SomeMethod"
的方法,分别为空字符串和空格。
如果该方法没有抛出正确的异常——正如在期望 类 中的 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);
}