views:

90

answers:

1

Hi Guys,

Came across the following MS Unit Test:

[TestMethod]
public void PersonRepository_AddressCountForSinglePerson_IsNotEqualToZero()
{
   // Arrange.
   Person person;

   // Act.
   person = personRepository.FindSingle(1);

   // Assert.
   Assert.AreNotEqual<int>(person.Addresses.Count, 0); 
}

I have never seen the use of generics when doing Assertions.

This is how i would write the Assertion:

// Assert.
Assert.AreNotEqual(person.Addresses.Count, 0);

What is the difference?

When i hover over the AreNotEqual overload i am using, the method is using the overload which compares two doubles (not sure why there isn't an int, int overload).

And if i do put the generic type-parameter of <int> in, Resharper says it's redundant.

So my question is - if the way i do it is still type-safe, why use generic assertions?

+5  A: 

So my question is - if the way i do it is still type-safe, why use generic assertions?

You are using the generic assertion now. The compiler sees the generic method, and chooses it at compile time. This is why Resharper is saying that the <int> is redundant - it's not because the method is redundant, but rather that the compiler can implicitly determine that the Assert.AreNotEqual<int> method is the proper method to use.

In general, you often don't need to specify the type on generics. This is what makes LINQ syntax bearable - without it, you'd need to specify the types on every method call in the chain, and anonymous types would be unusable.

That being said, there are times where specifying the generic type is required. This is mainly if the compiler cannot determine the type automatically, such as if there is no matching parameter in the argument list (ie: Foo.Create<MyClass>()), or if the type can't be determined for some other reason.

Reed Copsey
That explains it really well, thanks. So generally, we don't need to use the generic type parameter for most value-type assertions. I guess now if the compiler complains about an ambiguous assertion, i'll know to use the type parameter. Thanks.
RPM1984