gpt4 book ai didi

c# - 如何简化单元测试 DDD Value objects Equality with AutoFixture

转载 作者:太空狗 更新时间:2023-10-29 21:13:41 25 4
gpt4 key购买 nike

我目前正在使用 xUnit、Moq 和 AutoFixture 为我的域项目编写单元测试。让我们看看这个测试方法:

[Theory]
public void SameValueAs_OnOtherHasDifferentEmail_ReturnsFalse()
{
Fixture fix = new Fixture();
var sut = fix.CreateAnonymous<CoreAddress>();

var other = new CoreAddress(
sut.Firstname,
sut.Lastname,
sut.Company,
sut.Street,
sut.City,
sut.ZIP,
"other@email.com");

Assert.False(sut.SameValueAs(other));
}

如您所见,我正在测试类 CoreAddress 及其 SameValueAs 方法。为了测试每一种可能的情况,我必须创建测试方法 OnOtherHasDifferentFirstnameOnOtherHasDifferentLastname 等。这种模式可以吗?关于 AutoFixture 的使用,我能以某种方式简化吗?

最佳答案

这种方法与我自己的做法非常相似。鉴于几乎所有的自动化测试都围绕着测试一些实际结果是否等于一些预期结果,我从来没有真正理解为什么人们不想对相等性本身进行单元测试。

使用像上面这样的值对象,它很容易变得有点乏味,因为它会导致许多非常相似的测试。

您可以使用 xUnit.net 的一个 hack 是这样的:

[Theory]
[InlineData("other first name", null, null, null, null, null, null)]
[InlineData(null, "other last name", null, null, null, null, null)]
[InlineData(null, null, "other company", null, null, null, null)]
[InlineData(null, null, null, "other street", null, null, null)]
[InlineData(null, null, null, null, "other city", null, null)]
[InlineData(null, null, null, null, null, "other zip", null)]
[InlineData(null, null, null, null, null, null, "other@email.com")]
public void EqualsIsFalseWhenAtLeastOneValueDiffers(
string firstName,
string lastName,
string company,
string street,
string city,
string zip,
string email)
{
Fixture fix = new Fixture();
var sut = fix.CreateAnonymous<CoreAddress>();

var other = new CoreAddress(
firstName ?? sut.Firstname,
lastName ?? sut.Lastname,
company ?? sut.Company,
street ?? sut.Street,
city ?? sut.City,
zip ?? sut.Zip,
email ?? sut.Email);

Assert.False(sut.Equals(other));
}

然而,虽然它很紧凑,但我不太热衷于做这样的事情,因为测试本身的圈复杂度为 8 - 这大约是 7 太多了......只有输入值的轻微配置错误可能破坏测试并最终产生假阳性或假阴性。

另一方面,我们都是程序员,如果事情变得重复,我们该怎么办?

写一些代码来消除乏味。这基本上就是 AutoFixture.Idioms 的内容project 是关于,虽然它目前没有像上面那样的封装测试,但它可能会在未来得到一个......它是开源的,我们偶尔会接受 pull requests ;)

关于c# - 如何简化单元测试 DDD Value objects Equality with AutoFixture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12051087/

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