Search The Blog
Latest Posts
Twitter: @RoyOsherove
About this site

TDD in .NET Online Course

TDD and BDD in Ruby Online Course



This site aims to connect all the dots of my online activities - from tools, books blogs and twitter accounts, to upcoming conferences, engagements and user group talks.

« Introducing FxCopUnit - A framework for integrated FxCop rule testing | Main | Blogger Dinner This Wednesday »

Writing real unit tests for your custom FxCop rules

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


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);



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.


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

PrintView Printer Friendly Version

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
Web Analytics