Update: You might also be interested in FxCopUnit for FxCop Integration testing.

It’s possible to create elegant small tests which require little to no configuration whatsoever that test out your custom rule’s ability to verify problems. (I'll be discussing a framework for FxCop integration testing in a later post)

Here’s a sample unit test:

You'll need to add a reference to three libraries (on my machine they were located under C:\Program Files\Microsoft Visual Studio 8\Team Tools\Static Analysis Tools\FxCop\ )

  • FxCopCommon.dll
  • FxCopSDK.dll
  • Microsoft.Cci.dll

[Test]

public void InvokeMyRuleAgainstTheCurrentMethod()

{

MethodInfo someMethodInfo = MethodBase.GetCurrentMethod() as MethodInfo;

Microsoft.Cci.Method methodData = Microsoft.Cci.Method.GetMethod(someMethodInfo);

MyRule ruleUnderTest = new MyRule();

ProblemCollection problems = ruleUnderTest.Check(methodData);

Assert.Greater(0,problems.Count);

}

A custom rule can accept many kinds of inputs, but ultimately the most important ones are “Member” and “TypeNode”.

Here’s the hiearchy for Member these

(thanks to Resharper  - Small tip: put the caret on a type name and press Ctrl-Alt-H):

So the only question remains: how to you transform a simple reflection MethodInfo or EventInfo or FieldInfo or Type into the corresponding Member type in Microsoft.Cci?

It’s pretty simple: For each "thing" you'd like to transform There’s a static method on the counter "thing" to get that transformation. In the test above to get a Method object, I used the static Method.GetMethod(MethodInfo) to get what I need. You’ll find the same thing for Event, TypeNode and many others.

All you need is to create a new instance of your custom rule (without needing FxCop engine at all), and invoking it’s Check method with the data you have specified after transformation.

The Asserts should take place against the ProblemCollection object that you need to get back.

Voila!

You have yourself a true unit test with FxCop custom rules (or as close as possible to one..).

Introducing FxCopUnit - A framework for integrated FxCop rule testing

Blogger Dinner This Wednesday