Skip to content

Xunit 断言匿名类型 ​

使用反射来判断 ​

csharp
public class MyTestClass
{
    [Fact]
    public void GetAnonymous_Should_Return_Correctly()
    {
        var result = GetAnonymous();

        var id = (int)result.GetType().GetProperty("Id").GetValue(result);
        Assert.Equal(123, id);

        var text = (string)result.GetType().GetProperty("Text").GetValue(result);
        Assert.Equal("Abc123", text);
    }

    public object GetAnonymous()
    {
        var anonymous = new { Id = 123, Text = "Abc123", Test = true };
        return anonymous;
    }
}

使用Dynamic关键字 ​

我们需要先创建一个扩展方法如下

csharp
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;

namespace Malema.net
{
    public static class ObjectExtension
    {
        public static ExpandoObject ToExpandoObject(this object obj)
        {
            var expando = new ExpandoObject();

            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(obj.GetType()))
            {
                expando.TryAdd(property.Name, property.GetValue(obj));
            }

            return (ExpandoObject)expando;
        }
    }
}

接下来我们的单元测试就可以改成如下的形式了

csharp
public class MyTestClass
{
    [Fact]
    public void GetAnonymous_Should_Return_Correctly()
    {
        dynamic result = GetAnonymous().ToExpandoObject();

        Assert.Equal(123, result.Id);
           
        Assert.Equal("Abc123", result.Text);
    }

    public object GetAnonymous()
    {
        var anonymous = new { Id = 123, Text = "Abc123", Test = true };
        return anonymous;
    }
}

简单就是美