Practical ASP.NET

ConventionTests, Part 2: Creating Custom Conventions in ASP.NET

Now that you know how to use them (see Part 1 if you don't), it's time to create custom ones.

Last time, we introduced the open source ConventionTests library. If you are new to ConventionTests be sure to check that article out first.

While ConventionTests comes with a number of pre-built supplied conventions, it is also possible to create your own custom conventions and then use them in your test code.

In this example we're going to create our own custom convention that we can use to check that all interfaces follow the traditional naming convention of starting with the letter "I".

The first thing we need to do is create a new class in our test project. Assuming that the TestStack.ConventionTests NuGet package is installed in the test project, our new class can implement the required ConventionTests interface.

If we want to inspect and check the types in the production code project we implement the IConvention<Types> interface. This interface defines a couple of members: an Execute method where our custom verification code will go; and the ConventionReason string property.

The Execute method has the following signature: public void Execute(Types data, IConventionResultContext result). The data parameter will contain a list of all the types we need to check, this is the list of types that are selected by us in our actual unit test code. The result parameter is used to signal back to our actual test whether any of the types in data did not meet the convention.

To complete the custom convention checking logic in our custom convention we call the Is method of the result object. This method takes a string representing the title of the convention when it is output in the test output. The second parameter of the Is method takes a list of all the types that have failed to meet the custom convention. If there are any types in this list the test will fail.

The ConventionReason property allows a descriptive explanation of what the custom convention represents.

Listing 1 shows our custom interface-naming convention.

Listing 1: Custom Interface-Naming Convention.

using System.Linq;
using TestStack.ConventionTests;
using TestStack.ConventionTests.ConventionData;

namespace MyClassLibrary.Tests
{
    public class InterfaceNamingConvention : IConvention
    {
        public void Execute(Types data, IConventionResultContext result)
        {
            // Find any types passed to our custom convention from the test code
            // that are interfaces and that also don't start with 'I'
            var interfacesWithBadNames = data.TypesToVerify.Where(x =>  x.IsInterface &&
                                                           !x.Name.StartsWith("I"));

            // Once we have a list, if it contains > 0 types the convention will
            // fail and so will the tests
            result.Is("Interfaces must begin with the letter 'I'.", interfacesWithBadNames);
            
        }

        public string ConventionReason
        {
            get
            {
                return "The naming convention is to start all interface names with the letter 'I'.";
            }
        }
    }
}.

To use this convention in an actual unit test, our custom convention is treated the same way as one of the pre-built suppled conventions:

[Test]
public void AllInterfacesShouldBeNamedCorrectly()
{
    var typesToCheck = Types.InAssemblyOf<MyClassLibrary.SomeClassInAssemblyBeingTested>();

    var convention = new InterfaceNamingConvention();

    Convention.Is(convention, typesToCheck);
}.

Notice in the above test, we are creating an instance of our custom convention rather than one that comes out of the box with ConventionTests.

If we now define a couple of interfaces in our production code "MyClassLibrary" project as follows:

public interface IEatable
{
}

public interface IDrinkable
{
}.

When we run our unit test, it will pass (see Figure 1) because both of the preceding interfaces start with I.

Passing Custom Convention Test
[Click on image for larger view.] Figure 1. Passing Custom Convention Test

If we now change IDrinkable to just Drinkable (no preceding I) and run the test again it will fail (see Figure 2):

public interface IEatable
{
}

public interface Drinkable
{
}.
Failing Custom Convention
[Click on image for larger view.] Figure 2. Failing Custom Convention

If we check the output from the test we can see the following:

'Interfaces must begin with the letter 'I'.' for 'Types in MyClassLibrary'
--------------------------------------------------------------------------

          MyClassLibrary.Drinkable
.

Here we can see the detail of the failing convention, namely that the interface Drinkable is named incorrectly.

I hope this article and the last one was a helpful look at convention testings. Let me know your thoughts on this and future topics we can cover.

About the Author

Jason Roberts is a Microsoft C# MVP with over 15 years experience. He writes a blog at http://dontcodetired.com, has produced numerous Pluralsight courses, and can be found on Twitter as @robertsjason.

comments powered by Disqus

Featured

Subscribe on YouTube