繁体   English   中英

您如何测试枚举标记组合?

[英]How do you test an enum flag combination?

假设我有一个枚举标志:

[Flags]
public enum ColorType
{
    None = 0,
    Red = 1 << 0,
    White = 1<<1,
    Yellow = 1 << 2,
    Blue = 1 << 3,
    All = Red | White | Yellow | Blue
}

我有以下函数,该参数是标志的组合,例如DoSomething(ColorType.Blue | ColorType.Yellow)。

public void DoSomethingr(ColorType theColorTypes)
{
        if (theColorTypes.HasFlag(All)) Foo1();
        if (theColorTypes.HasFlag(White) && theColorTypes.HasFlag(Red) )  Foo2();
        if (!theColorTypes.HasFlag(Blue)) Foo3();
        . . . 
}

有没有一种简单的方法可以测试所有可能的标志按位组合?

[Test] 
public void Test1(ColorType.Red | ColorType.Yellow | ColorType.White) 

[Test]
public void Test1(ColorType.Red | ColorType.Yellow | ColorType.white | ColorType.Blue) 

谢谢

循环所有可能的值,并将其放入TestCaseSource ,以为每个枚举值生成不同的测试:

public IEnumerable<ColorType> TestCaseSource 
{ 
    get
    {
        int start = (int)ColorType.None;
        int count = (int)ColorType.All - start + 1;
        return Enumerable.Range(start, count).Select(i => (ColorType)i); 
    } 
}

[TestCaseSource("TestCaseSource")]
public void Test1(ColorType colorType)
{
    // whatever your test is
}

只需花费我两美分,就可以改进它以接受“其他”值类型,但是当您喜欢扩展方法时,也可以选择:

public static class EnumExtensions
{
    public static bool HasFlags<TEnum>(this TEnum @enum,
                                       TEnum flag,
                                       params TEnum[] flags)
        where TEnum : struct
    {
        var type = typeof(TEnum);
        if (!type.IsEnum)
            throw new ArgumentException("@enum is not an Enum");

        var hasFlagsMethod = type.GetMethod("HasFlag");
        var hasFlag = new Func<TEnum, bool>(e =>
        {
            return (bool)hasFlagsMethod.Invoke(@enum, new object[] { e });
        });

        // test the first flag argument
        if (!hasFlag(flag))
            return false;

        // test the params flags argument
        foreach (var flagValue in flags)
        {
            if (!hasFlag(flagValue))
                return false;
        }
        return true;
    }
}


[Flags]
public enum ColorType
{
    None = 0,
    Red = 1 << 0,
    White = 1 << 1,
    Yellow = 1 << 2,
    Blue = 1 << 3,
    All = Red | White | Yellow | Blue
}

这样称呼它:

class Program
{
    static void Main(string[] args)
    {
        var color = ColorType.Red;
        Console.WriteLine(color.HasFlags(ColorType.Red)); // true;
        Console.WriteLine(color.HasFlags(ColorType.Red, ColorType.Blue)); // false;

        color = ColorType.All;
        Console.WriteLine(color.HasFlags(ColorType.Red, ColorType.Blue)); // true;

        Console.ReadLine();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM