You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用FluentAssertions断言同类型对象的所有属性均不相同?

使用FluentAssertions断言同类型对象所有属性均不相同

FluentAssertions没有内置的直接断言“所有属性都不同”的方法,但可以结合反射和自定义逻辑实现需求:

  • 先通过反射获取对象的所有公共实例属性
  • 遍历每个属性,检查两个对象的属性值是否相等
  • 断言不存在任何相等的属性,只要有一个属性值相同就触发断言失败

基础实现代码(值类型/简单引用类型)

using System.Reflection;
using FluentAssertions;

// 示例类
public class MyClass
{
    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime RegisterDate { get; set; }
}

// 测试逻辑
var objA = new MyClass { Name = "Alice", Age = 30, RegisterDate = new DateTime(2020, 1, 1) };
var objB = new MyClass { Name = "Bob", Age = 25, RegisterDate = new DateTime(2021, 5, 5) };

// 获取类的所有公共实例属性
var properties = typeof(MyClass).GetProperties(BindingFlags.Public | BindingFlags.Instance);

// 检查是否存在值相等的属性
var hasMatchingProp = properties.Any(prop => 
    object.Equals(prop.GetValue(objA), prop.GetValue(objB)));

// 断言没有匹配的属性
hasMatchingProp.Should().BeFalse("两个对象的所有属性必须完全不同");

处理引用类型的深比较

如果对象包含需要深比较的引用类型属性,可以借助FluentAssertions的BeEquivalentTo来判断单个属性的等价性:

var hasMatchingProp = properties.Any(prop => 
{
    var valA = prop.GetValue(objA);
    var valB = prop.GetValue(objB);
    
    try
    {
        valA.Should().BeEquivalentTo(valB);
        return true;
    }
    catch (AssertionFailedException)
    {
        return false;
    }
});

hasMatchingProp.Should().BeFalse("两个对象的所有属性(包括嵌套属性)必须完全不同");

可选优化

如果需要排除某些属性不参与检查,可以在获取属性列表时过滤:

var properties = typeof(MyClass)
    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
    .Where(prop => prop.Name != "IgnoreThisProp");

内容的提问来源于stack exchange,提问作者Andrei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 18:25:18