Tuesday, July 19, 2005

Testing Nullable in NUnit

I've been learning about Nullable types in .NET 2.0. They're very handy, especially in the case of Business Entities (Data Transfer Objects) which interract with a database. Database fields may have null entries, which are a pain in the keester when it comes to value types like int, bool, and structures. I've also been figuring out how NUnit deals with Nullable types. It's not clear in the documentation I saw, so I had to do a bit of trial and error. Assert.AreEqual() won't directly compare two Nullable types, but you can use the Nullable.Compare() method and check its return as needed. Below is an example of a underborder test using Nullable.Compare(). I'm testing that my bounds checking in my PostEntity's PostID property correctly barfs when it sees a negative number. (I don't want negative IDs for my posts.) PostEntity.PostID is a Nullable<int>. Note that you've got to pass it a Nullable int as well; Plain Old Int won't work. Note that Nullable.Compare() returns the usual suspects for a compare operation: 0 if equal, -1 if the first param is smaller, 1 if it's larger. [Test] public void CheckPersonIDNegative() {     PersonEntity pEnt = new PersonEntity();     Nullable negVal = -1;     try     {        pEnt.PersonID = negVal;        Assert.Fail("Expected ArgumentOutOfRangeException");     }     catch (ArgumentOutOfRangeException ae)     {        Assert.AreEqual(0, Nullable.Compare(negVal,        (Nullable)ae.ActualValue),"Failed compare");     }     catch (Exception ex)     {        Assert.Fail("Unexpected Exception: " + ex.Message);     }     finally     {        pEnt = null;     } }

No comments:

Post a Comment