Skip to main content

Convention Tests

ยท One min read

Convention Tests, AKA: Protecting "future me"

I needed a way to ensure that I didn't stupidly include internal data types in WebAPI methods

Installationโ€‹

Install-Package TestStack.ConventionTests

Example Useโ€‹

ApiControllersShould.cs
[TestFixture]
public class ApiControllersShould
{
[Test]
public void UseDtoParameterTypes()
{
// Define some data
var methods = Methods.InAssemblyOf("Api Controller Methods",
t => t.Where(p => p.DeclaringType.BaseType == typeof(ApiControllerBase)
&& p.CustomAttributes.Any(a => a.AttributeType == typeof(RouteAttribute))));

// Apply convention to data
Convention.Is(new MethodParametersAreDto("DanceScore.DataContracts"), methods);
}
}

IConvetion Implementationโ€‹

MethodParametersAreDto.cs
public class MethodParametersAreDto : IConvention
{
private readonly string _namespacePrefix;

public MethodParametersAreDto(string namespacePrefix)
{
_namespacePrefix = namespacePrefix;
}

public void Execute(Methods data, IConventionResultContext result)
{
var methods = data.MethodsToVerify
.Where(m => !m.GetParameters()
.All(p => p.ParameterType.Namespace.StartsWith("System")
|| p.ParameterType.Name.StartsWith(_namespacePrefix)));

result.Is(ConventionReason, methods);
}

public string ConventionReason
{
get { return "All Method Parameters MUST be in System or DataContracts Namespace"; }
}
}