NUnit TestCase attribute with reflection for checking null field handling

I recently had a need to write some unit (actually integration) tests which would check how I handled field being null. Without using the [TestCase] attribute of NUnit my tests would have looked something like this …

public void validation_failure_identifier_null_400_expected()
{
    // Arrange
    var resource = CreateCompleteResource();
    resource.Identifier = null;
    var jsonString = JsonPrettifier.Prettify(resource);

    // Act
    var result = Service.Post(jsonString);

    // Assert
    result.Message.CheckForValidationError("Identifier");
}

public void validation_failure_forename_null_400_expected()
{
    // Arrange
    var resource = CreateCompleteResource();
    resource.Forename = null;
    var jsonString = JsonPrettifier.Prettify(resource);

    // Act
    var result = Service.Post(jsonString);

    // Assert
    result.Message.CheckForValidationError("Forename");
}

… and so on.

BUT, by using a little reflection in conjunction with the [TestCase] attribute of NUnit, I can do this …

private string GenerateJsonAndSetFieldTo(string fieldName, string value)
{
    var resource = CreateCompleteResource();
    var type = resource.GetType();
    var prop = type.GetProperty(fieldName);
    prop.SetValue(resource, value, new object[0]);
    var jsonString = JsonPrettifier.Prettify(resource);
    return jsonString;
}

[TestCase("Identifier")]
[TestCase("Forename")]
public void validation_failure_400_expected(string fieldName)
{
    // Arrange
    var jsonString = GenerateJsonAndSetFieldTo(fieldName, null);

    // Act
    var result = Service.Post(jsonString);

    // Assert
    result.Message.CheckForValidationError(fieldName);
}

Obviously I have more TestCase’s than shown here, I didn’t want to bore you all with them! Less tests to maintain, easier to add null checking for other fields and it also looks neater in my test runner of choice.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s