Lambda表达式作为xUnit中的内联数据 [英] Lambda expression as inline data in xUnit

查看:55
本文介绍了Lambda表达式作为xUnit中的内联数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对xUnit还是很陌生,这是我想要实现的目标:

I'm pretty new to xUnit and here's what I'd like to achieve:

[Theory]
[InlineData((Config y) => y.Param1)]
[InlineData((Config y) => y.Param2)]
public void HasConfiguration(Func<Config, string> item)
{
    var configuration = serviceProvider.GetService<GenericConfig>();
    var x = item(configuration.Config1); // Config1 is of type Config

    Assert.True(!string.IsNullOrEmpty(x));            
}

基本上,我有一个 GenericConfig 对象,其中包含 Config 和其他类型的配置,但是我需要检查每个参数是否有效.由于它们都是字符串,因此我想简化使用 [InlineData] 属性,而不是编写N个相等测试.

Basically, I have a GenericConfig object which contains Config and other kind of configurations, but I need to check that every single parameter is valid. Since they're all string, I wanted to simplify using [InlineData] attribute instead of writing N equals tests.

不幸的是,我得到的错误是无法将lambda表达式转换为类型'object []',因为它不是委托类型",这很清楚.

Unfortunately the error I'm getting is "Cannot convert lambda expression to type 'object[]' because it's not a delegate type", which is pretty much clear.

您对如何克服这一点有任何想法吗?

Do you have any idea on how to overcome this?

推荐答案

实际上,我能够找到一种比Iqon提供的解决方案更好的解决方案(谢谢!).

Actually, I was able to find a solution which is a bit better than the one provided by Iqon (thank you!).

显然, InlineData 属性仅支持原始数据类型.如果您需要更复杂的类型,则可以使用 MemberData 属性向单元测试提供来自自定义数据提供程序的数据.

Apparently, the InlineData attribute only supports primitive data types. If you need more complex types, you can use the MemberData attribute to feed the unit test with data from a custom data provider.

这是我解决问题的方法:

Here's how I solved the problem:

public class ConfigTestCase
{
    public static readonly IReadOnlyDictionary<string, Func<Config, string>> testCases = new Dictionary<string, Func<Config, string>>
    {
        { nameof(Config.Param1), (Config x) => x.Param1 },
        { nameof(Config.Param2), (Config x) => x.Param2 }
    }
    .ToImmutableDictionary();

    public static IEnumerable<object[]> TestCases
    {
        get
        {
            var items = new List<object[]>();

            foreach (var item in testCases)
                items.Add(new object[] { item.Key });

            return items;
        }
    }
}

这是测试方法:

[Theory]
[MemberData(nameof(ConfigTestCase.TestCases), MemberType = typeof(ConfigTestCase))]
public void Test(string currentField)
{
    var func = ConfigTestCase.testCases.FirstOrDefault(x => x.Key == currentField).Value;
    var config = serviceProvider.GetService<GenericConfig>();
    var result = func(config.Config1);

    Assert.True(!string.IsNullOrEmpty(result));
}

我可能会想出更好或更干净的东西,但是现在它可以工作并且代码不会重复.

I could maybe come up with something a bit better or cleaner, but for now it works and the code is not duplicated.

这篇关于Lambda表达式作为xUnit中的内联数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆