我想知道我是否可以做一个测试的全局配置。我知道我可以这样比较这个物体:
x.Should().BeEquivalentTo(y, opt => opt.Excluding(z => z.Member)
但是我希望我的测试中的所有方法都使用这个配置。
daolsyd01#
要从特定类型中排除成员,可以创建自定义IMemberSelectionRule。要对所有测试使用该选择规则,请在单元测试框架的某些设置方法中使用静态AssertionOptions.AssertEquivalencyUsing。要知道AssertionOptions.AssertEquivalencyUsing会改变Fluent Assertions的静态状态,所以如果你正在并行运行测试,那么应该在运行 * 任何 * 测试之前调用它。对于NUnit,[OneTimeSetUp]位于[SetUpFixture]中,而不是位于命名空间中。
IMemberSelectionRule
AssertionOptions.AssertEquivalencyUsing
[OneTimeSetUp]
[SetUpFixture]
using FluentAssertions; using FluentAssertions.Equivalency; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; [SetUpFixture] public class MySetUpClass { [OneTimeSetUp] public void RunBeforeAnyTests() { AssertionOptions.AssertEquivalencyUsing(e => e.Using(new MyNamespace.MyClassSelectionRule())); } } namespace MyNamespace { class MyOuterClass { public MyInnerClass MemberToInclude { get; set; } public int MemberToExclude { get; set; } } class MyInnerClass { public int AnotherMemberToInclude { get; set; } public int MemberToExclude { get; set; } } internal class MyClassSelectionRule : IMemberSelectionRule { public bool IncludesMembers => false; public IEnumerable<IMember> SelectMembers(INode currentNode, IEnumerable<IMember> selectedMembers, MemberSelectionContext context) => selectedMembers.Where(e => !(e.DeclaringType.Name == nameof(MyOuterClass) && e.Name == nameof(MyOuterClass.MemberToExclude))); } [TestFixture] public class UnitTest1 { [Test] public void Ignore_the_member_MemberToExclude_on_MyOuterClass() { var subject = new MyOuterClass { MemberToInclude = new MyInnerClass { AnotherMemberToInclude = 42, MemberToExclude = 42 }, MemberToExclude = 1 }; var expectation = new MyOuterClass { MemberToInclude = new MyInnerClass { AnotherMemberToInclude = 42, MemberToExclude = 42 }, MemberToExclude = 2 }; subject.Should().BeEquivalentTo(expectation); } [Test] public void Do_not_ignore_the_member_MemberToExclude_on_MyInnerClass() { var subject = new MyOuterClass { MemberToInclude = new MyInnerClass { MemberToExclude = 1 }, }; var expectation = new MyOuterClass { MemberToInclude = new MyInnerClass { MemberToExclude = 2 }, }; Action act = () => subject.Should().BeEquivalentTo(expectation); act.Should().Throw<AssertionException>(); } } }
1条答案
按热度按时间daolsyd01#
要从特定类型中排除成员,可以创建自定义
IMemberSelectionRule
。要对所有测试使用该选择规则,请在单元测试框架的某些设置方法中使用静态
AssertionOptions.AssertEquivalencyUsing
。要知道AssertionOptions.AssertEquivalencyUsing
会改变Fluent Assertions的静态状态,所以如果你正在并行运行测试,那么应该在运行 * 任何 * 测试之前调用它。对于NUnit,[OneTimeSetUp]
位于[SetUpFixture]
中,而不是位于命名空间中。