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

  • Hands On: New VS Code Insiders Build Creates Web Page from Image in Seconds

    New Vision support with GitHub Copilot in the latest Visual Studio Code Insiders build takes a user-supplied mockup image and creates a web page from it in seconds, handling all the HTML and CSS.

  • Naive Bayes Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the naive Bayes regression technique, where the goal is to predict a single numeric value. Compared to other machine learning regression techniques, naive Bayes regression is usually less accurate, but is simple, easy to implement and customize, works on both large and small datasets, is highly interpretable, and doesn't require tuning any hyperparameters.

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

Subscribe on YouTube

Upcoming Training Events