Home > CodeProject, Development, SharePoint 2013, Uncategorized > Avoiding SharePoint Magic Numbers in Unit Testing

Avoiding SharePoint Magic Numbers in Unit Testing

Unit testing really is good. No surprise to those who do it but recently we had a test go red when changing how we configure Enhanced Records Manager, see
Appropriate use of AppInstalled for a Provider Hosted SharePoint App for more details.

Not a problem we have broken something lets fix it.

It turns out that every properties metadata was being added twice to our configuration database.  Simple.  We had inadvertently called the ImportProperties method twice.  So all we have to do is remove the wrong call and we are away.  Hold on isn’t import properties supposed to update if the same property is imported twice not add.  Lets dig further.

So when we unit test we don’t use SharePoint, its too ‘heavy’, but we have abstracted it in the design to an Interface called the RecordRepository Interface which has ‘generic’ methods, such as GetProperties which returns all the properties the Records Management system.  This gives us two great benefits:

  1. We can replace it for unit testing by a lightweight RecordsRepository currently a pure in memory one.
  2. We can use Records Repositories other than SharePoint by ‘merely’ replacing the Records Repository as it only deals with access, not logic.

The ImportProperties unit tests weren’t failing so the actual logic was okay, well we all know GIGO (Garbage In, Garbage Out) so if the output is wrong but the logic is right it must be the input.  And Lo and behold so it was.  Our Unit test Records Repository generates a defined set of properties using Guids as their unique identifiers.  Good.  Problem was they were generated each time the GetProperties method was called so if you called it twice you get two sets of properties identical in all but identifier.

A long preamble but it got me thinking.  Why hadn’t we just used the known identifiers for the SharePoint built in fields?  Title is always {fa564e0f-0c70-4ab9-b863-0177e6ddd247}.  We didn’t so why?  Ah yes go back to point 2 the design of ERM is that it is repository agnostic.  If we had just used the ‘magic’ value when we changed the actual Records Repository we could have been in the position where our unit tests passed fine but it failed in practice because we had been lazy and also used the magic value somewhere in the business logic.

So we generated Guids just for our Unit test Records Repository as fixed Guids and that sorted that.

Cheers

Sebastian

  1. No comments yet.
  1. No trackbacks yet.

Leave a comment