Meta tests
time to read 3 min | 402 words
I found this test fixture hilarious.
[TestFixture] public class ValidateNamingConventions { private System.Type[] types; [SetUp] public void Setup() { types = typeof(ISearchFactory).Assembly.GetExportedTypes(); } [Test] public void InterfacesStartsWithI() { foreach (System.Type type in types) { if(type.IsInterface==false) continue; Assert.IsTrue(type.Name.StartsWith("I"),type.Name); } } [Test] public void FirstLaterOfMethodIsCapitalized() { foreach (System.Type type in types) { foreach (MethodInfo method in type.GetMethods()) { Assert.IsTrue(char.IsUpper(method.Name[0]), type.FullName + "." + method.Name); } } } [Test] public void AttributesEndWithAttribute() { foreach (System.Type type in types) { if (type.IsAssignableFrom(typeof(Attribute))) continue; Assert.IsTrue(type.Name.EndsWith("Attribute"), type.Name); } } }
Comments
Well I started reading it thinking "how ridiculous" ... but now I'm not so sure ... in the absense of FxCop or NDepend ... it is one way of ensuring coding standards are being applied, though I grant a rather ingenious one :)
Looks like reinventing the weel
May be better put this into PostBuild event?
I prefer Agent Smith plugin for Resharper - it shows me when code convention is broken
Definitely hilarious. Really should be using MbUnit's TestSuite feature or your preferred test framework's equivalent so you get one test passing or failing for each interface, method, and attribute, not just a test that fails on the first problem it finds.
They forgot to add
To catch the spelling error in "FirstLaterOfMethodIsCapitalized".
that is very funny, and a very cool idea. however i don't think i would ever want to include a test like that as part of my continuous integration. it doesn't seem like it 'belongs' as a true unit test, perhaps it would be best used as a separate test from your standard unit tests.
Thats a bit hilarius.
I use Code Style Enforcer for this, it plays nicely with ReSharper. You can customize the rules.
Anyone tried Microsofts StyleCop?
I've tried StyleCop. It complained about some things we don't like ("always use 'this.' before accessing members", for example). We had literally several thousand violations. So we didn't pursue it any further.
I think you can turn off rules in StyleCop, but you cant change a rule that says that private fields should start with m_ when you want only _.
So you have to disable that rule and implement your own custom rule.
This kind of test is perfect for continuous integration as it will reveal convention mistakes for whole team extremely quickly and well, continuously.
Function AttributesEndWithAttribute should be corrected ...
if (type.IsAssignableFrom(typeof(Attribute)))
should be
if (type.IsAssignableFrom(typeof(Attribute)) == false)
Comment preview