Wednesday
Oct152008
Writing .NET code analysis rules as unit tests
Wednesday, October 15, 2008 at 1:36 in
tdd Writing assembly usage rules as unit tests turns out to be unexpectedly simple:
[Test]
public void Immutable_Types_Should_Be_Immutable()
{
var decorated = GlobalSetup.Types
.Where(t => t.Has<ImmutableAttribute>());
foreach (var type in decorated)
{
var count = type.GetAllFields().Count(f => !f.IsInitOnly && !f.IsStatic);
Assert.AreEqual(0, count, "Type {0} should be immutable", type);
}
}
This test (based on the functionality provided by the Lokad.Quality.dll from the Shared Libraries) does the job, but it is not logically a proper one, yet.
Proper test should dynamically emit one test case per type tested (something to be done through the NUnit extensibility model).
How do you define and enforce high-level coding rules in your projects?
Update on Monday, December 1, 2008 at 10:10 by
Rinat Abdullin
This test could be observed in the wild in the Lokad Shared Libraries (check out CodeQualityTests.cs).
Update on Monday, December 1, 2008 at 10:11 by
Rinat Abdullin
BTW, you might be interested in the post "How to ensure that complex methods are covered with tests" from the Test Driven Development category.
Reader Comments (4)
I sometimes use similar unit tests to enforce conventions in the code. For example in an ASP.NET MVC project, all controllers (inheriting Controller) should have a Controller suffix (XxxController).
I love autofac and recently upgraded my MVC Release 5 project to beta - but I seem to be getting the same error as this guy
http://groups.google.com/group/autofac/browse_thread/thread/68aaf55581392d08
Any news on this front or timeline for a fix ? Possible to respond to this thread?
Thanks :)
Andy,
I'm sure that you've read the thread, but just to ensure - Nick has updated Autofac to Beta on Oct 18.
[...] BTW, there is a simple unit-test to enforce that your classes are immutable. [...]