29 Aug

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

[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

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"; }
}
}