Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two Unit Test Assertions?

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?

like image 339
RPM1984 Avatar asked Oct 15 '10 00:10

RPM1984


1 Answers

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.

like image 65
Reed Copsey Avatar answered Oct 01 '22 08:10

Reed Copsey