Search code examples
c#unit-testingc#-4.0dynamics-crm-2011vs-unit-testing-framework

Should I make my Custom Unit Test Assert Class Non-Static?


I use the built in Visual Studio Unit Testing Tools to perform unit tests against CRM 2011. A lot of the tests are Asserting the creation of an Entity.

Assert.IsNull(service.GetFirstOrDefault<Contact>(contact.Id));

(the GetFirstOrDefault is an extension method that attempts to retrieve the contact by id from CRM, and returns null if not found)

I'd like to create my own Assert method that operates like this:

CrmAssert.Exists(service, contact);

At first I thought it would be a good idea to inherit from Assert, but alas, it is a static class. I then created a new static class like so:

public static class AssertCrm
{
    public static void Exists<T>(IOrganizationService service, T entity) where T : Entity
    {
        Exists(service, entity, null, null);
    }
    public static void Exists<T>(IOrganizationService service, T entity, string message) where T : Entity
    {
        Exists(service, entity, message, null);
    }

    public static void Exists<T>(IOrganizationService service, T entity, string message, params object[] parameters) where T: Entity
    {
        if (service.GetFirstOrDefault<T>(entity.Id) == null)
        {
            throw new AssertFailedException(message == null ? String.Format(message, parameters));
        }
    }
}

Called like so:

AssertCrm.Exists(service, contact);

This is fine, except that I really should be able to set the service, once, and not have to call it each time:

AssertCrm.Service = service;
AssertCrm.Exists(contact);
AssertCrm.Exists(campaign);
AssertCrm.Exists(etc...);

But I believe that Visual Studio will attempt to run tests multi-threaded, which means that when I set the Service static property, it could be overridden by a different service in a different test (As well as IOrganizationService not being thread-safe).

Do I need to make my AssertCrm class non-static so I don't have to worry about mutli-threading? Is there a simpler technique that I'm missing?


Solution

  • After some additional research I didn't find any reason that it should (has to) be a static class, and have since created it as a non-static class.

    One note to anyone else thinking of doing something similar: Do create static method overloads for all of your instance methods since ClassName.AssertMethod() really does make more sense a majority of the time vs new ClassName().AssertMethod()