Latest Replies
Wednesday
Oct152008

Writing .NET code analysis rules as unit tests

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?

« Productivity migration | Main | Another alternative to the Single Service Locator Interface »

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

October 15, 2008 | Unregistered CommenterFredrik

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

October 17, 2008 | Unregistered CommenterAndy

Andy,

I'm sure that you've read the thread, but just to ensure - Nick has updated Autofac to Beta on Oct 18.

October 20, 2008 | Unregistered CommenterRinat Abdullin

[...] BTW, there is a simple unit-test to enforce that your classes are immutable. [...]

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):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>