I am taking a semi-TDD approach to my most recent project. As I started writing my initial tests, it occurred to me that all of the ServiceLayer/Manager classes in my business layer inherit from a standard base class and that at least a few of the tests will be identical (except of course for the datatypes used). Each test class will also have essentially the same setup and breakdown.
So of course, I immediately fire up a new class and create a generic base class. I added a type parameter for the entity type that will be transported/manipulated through my Bll, one for the class being tested and another for the data access interface that I would be mocking through Rhino Mocks.
I added the internal and private members that would be used for setup and the test initialization method, commented it all out in my actual test class and added my inheritance. So far, so good. My tests ran, but they were still implemented in the original test class, so I commented them out, copied them into my base class and updated them to use my generic type arguments.
At this point, the “CreateInstance()” method that I was using to get a new instance of my target object caused a compiler error due to the fact that it called a constructor on my genric type argument that accepted a parameter. In order to pass in the mock for my data access interface, the parameter had to be there, but there is no way to specify constructor arguments in the constraints for generic type references.
I decided that making the “CreateInstance()” method abstract would give me access to it and then I would just have to add an implementation into my actual test classes… not a bad trade for the ability to “share” a group of core unit tests. So I marked the class as abstract, removed the method implementation, added the override into my actual test class and compiled.
At this point, my test project compiled with no problem, but my tests didn’t show up in test view. I compiled again, closed and re-opened my test class, closed and re-opened Visual Studio… still no tests in the test view window.
A quick Google search turned up this. I haven’t spent much time researching it at this point, but it seems that Visual Studio doesn’t recognize (or won’t run) Unit Tests that are defined in an abstract class. This problem is pretty specific to the unit testing framework that ships with Visual Studio. Sounds to me like this sort of thing would be possible if I were using NUnit (or some other xUnit framework) to do my unit testing.
The base class still seems to handle my setup and breakdown pretty well and I can use it for support methods that I share between tests so it isn’t a total loss, it just would have been nice to be able to inherit some tests as well.
If I find any new information, I will be sure to post it. If you know something I don’t (I’m sure you do but I mean something related…) feel free to share in the comments.
.NET, TDD, Tools, Unit Testing, Visual Studio
TDD, Unit Testing, Visual Studio