Kip Morgan
Kip Morgan

Reputation: 738

Which MSTest Assert.AreEqual method is preferred?

What is the recommended way to write a unit test assertion? Both the generic and non-generic versions pass, but I am concerned about unnecessary boxing, performance, and accuracy. I would like to create a general rule for coding standards so I can recommend doing it one way or the other.

    [TestMethod]
    public void TestMethod1()
    {
        Visibility hidden = Visibility.Hidden;

        Assert.AreEqual(Visibility.Hidden, hidden);

        Assert.AreEqual<Visibility>(Visibility.Hidden, hidden);
    }

Upvotes: 1

Views: 141

Answers (2)

Michael Gunter
Michael Gunter

Reputation: 12811

I'll add an additional $0.02:

As others said, in this case, the two are the same, because the first call (without the type parameter) still compiles to the same method due to type inference. With that in mind, the less verbose code would be preferred.

But suppose that, for some reason, the first call actually goes to the non-generic version that takes (object, object). As it turns out, the behavior of the two are exactly the same. The performance of the (object, object) could hypothetically be slightly worse than the generic form (or vice-versa -- who knows until you test it?). But since performance of unit tests are rarely a practical consideration, that concern is moot. Removing performance and behavior as considerations leaves only one consideration -- readability.

The first is more readable (less redundant, more concise without negative impact to readability) than the second. Therefore the first should be preferred over the second, always.

Upvotes: 0

hoodaticus
hoodaticus

Reputation: 3880

Those are the same method call, just written differently. The Visibility type parameter is inferred from the type of the arguments.

When type can be inferred, the typical style is to not include it.

Upvotes: 4

Related Questions