Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Assert.AreEqual(1.0, double.NaN, 1.0) pass?

Short question, why does Assert.AreEqual(1.0, double.NaN, 1.0) pass? Whereas Assert.AreEqual(1.0, double.NaN) fails.

Is it a bug in MSTest (Microsoft.VisualStudio.QualityTools.UnitTestFramework) or am I missing something here?

Best regards, Egil.


Update: Should probably add, that the reason behind my question is, that I have a bunch of unit tests that unfortunately passed due to the result of some linear algebraic matrix operation being NaN or (+/-)Infinity. The unit tests are fine, but since Assert.AreEqual on doubles with a delta will pass when actual or/and expected are NaN or Infinity, I was left to believe that the code I was testing was correct.

like image 921
Egil Hansen Avatar asked Nov 22 '09 21:11

Egil Hansen


People also ask

What is assert AreEqual()?

Tests whether the specified objects are equal and throws an exception if the two objects are not equal. Different numeric types are treated as unequal even if the logical values are equal.

How do you compare two objects in assert?

Assert. AreEqual() compares references. Usually when comparing lists I compare the count of the items and than some properties of one exact item in the list or directly the item in the list (but again it is the reference).


1 Answers

Be careful. NaN is weird, somewhat like null in many DBMSs, and you shouldn't be comparing values to it (either directly, or with Assert.AreEqual). From the docs for Double.NaN:

Use IsNaN to determine whether a value is not a number. It is not possible to determine whether a value is not a number by comparing it to another value equal to NaN.

double zero = 0;
Console.WriteLine((0 / zero) == Double.NaN);  // prints false
Console.WriteLine(Double.IsNaN(0 / zero));  // prints true

You'd have to peer at the internals of Assert(double, double, double) to see what's going on, but in general, you're depending on undefined behavior relative to NaN.

like image 85
Michael Petrotta Avatar answered Nov 15 '22 21:11

Michael Petrotta