TDD using Interfaces

One of the tenants of TDD is that the tests are written, well, first.  The biggest problem I have with writing the tests first is one of developer productivity.  Call me a slave to tooling, but I really use intellisense when I code, so much to the point that I don’t even realize that I am using it.  With TDD, I can’t use Intellisense because the object has not been written yet.  As a way out of this problem, I thought of using interfaces.  I write the interface, write the test, then write the class under test.  I thought I would put my theory to the test with a basic example.  I created an interface like so:

1 using System; 2  using System.Collections.Generic; 3  using System.Linq; 4  using System.Text; 5  using Com.Tff.Patent.Data; 6 7  namespace Com.Tff.Patent.Domain 8 { 9 public interface IDoctrineFactory 10 { 11 static Doctrine GetDoctrine(int doctrineId); 12 static List<Doctrine> GetDoctrines(); 13 static List<Doctrine> GetDoctrines(int issueId); 14 } 15 } 16  

I then created a test like so:

1 [TestMethod] 2 public void GetDoctineReturnsCorrectValue() 3 { 4 IDoctrineFactory.GetDoctrine(1); 5 string expected = "aaa"; 6 string actual = doctrine.DoctrineName; 7 Assert.AreEqual(expected, actual); 8 9 } 10

However, I got a compiler error:

1 Error 1 The modifier 'static' is not valid for this item 2 3 Error 2 The modifier 'static' is not valid for this item 4 5 Error 3 The modifier 'static' is not valid for this item 6 7

That’s right – interfaces can’t be marked as static.  So then I thought of newing up a class in my test:

1 IDoctrineFactory doctrineFactory = new IDoctrineFactory(); 2 doctrineFactory.GetDoctrine(1); 3

The fact that I didn’t get intellisense was my first clue. The compiler error was my second:

1 Error 3 Cannot create an instance of the abstract class or interface

So then I created a concrete class using the refactoring tools in VS2010:

1 public class DoctrineFactory: IDoctrineFactory 2 { 3 public Data.Doctrine GetDoctrine(int doctrineId) 4 { 5 throw new NotImplementedException(); 6 } 7

This is better – I will get red b/c I have not implemented my methods yet – and I get intellisense in my unit tests. So for me, TDD is:

  • Write interface
  • Implement interfaces via VS2010
  • Write tests to get red
  • Write code logic to get to green

That way I get the intent behind TDD with modern tooling support.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: