开发者

Assert.AreEqual to not fail when comparing an enum and an int

I'm not sure if this is doable, but I will just开发者_如何学Python give a shot.

I am calling Assert.AreEqual() method. For the parameters, I'm passing...

  1. an enum value which has Int32 as the underlying type because I didn't specify the base type

  2. an int (Int32) value

Assert fails because it sees that the enum is not int (which is definitely correct).

However, is there a way to make this Assert pass when the enum has the correct int value as the 2nd parameter?

I can cast the enum to int and have it a quick fix, but it's really ugly.

I was expecting some kind of overriding a method that Assert uses to compare 2 different objects and implicitly make that enum type look like an int. However, I wasn't successful at finding any hint/answer around that so far.

Someone suggested to create a type converter and use the TypeConverterAttribute to get around. If this works for sure and is the only way to do it, I would; however, it does seem a lot of unnecessary work.


By calling Assert.AreEqual(enum, int), you are calling the Assert.AreEqual(object, object) method, as there is no overload that has an enum and an int as parameters.

I do not think that casting the enum to an int is ugly - in fact I think it is perfectly acceptable and a very common technique. If you were doing a normal equality comparison (ie. 1 == MyEnum.Value), you would get a compiler error as there is no implicit conversion, only an explicit one which requires a cast to work.

A type converter may work, but you need to ask yourself if doing that will actually give you any real benefit for the amount of effort involved. Personally, I would just leave the cast to an int.

If you are asserting something like the return value of a method call, why not just assert based on what value you expect?

MyEnum actual = SomeMethod();
Assert.AreEqual(MyEnum.Value, actual);

This does not require the cast as the two types are the same, and you are asserting the expected value.


I was expecting some kind of overriding a method that Assert uses to compare 2 different objects and implicitly make that enum type look like an int.

That won't work, since Assert.AreEqual is a static method, and you cannot override static methods, nor can you add overloads for static methods through extension methods.

Anyway, even if you could, you would violate the contract for Assert.AreEqual. You want to have Assert.AreEqual(myEnum.One, 1) yield true, although myEnum.One.Equals(1) as well as 1.Equals(myEnum.One) return false. That's inconsistent.

Casting to int is not ugly, it's the correct solution to your problem. After all, you want to check if the numerical value of the enum matches some integer. If that's what you want to check, write it down like this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜