Good evening,
I am working to get my head around unit testing and I’m having a little trouble determining how far I can push unit testing before it turns into integration testing.
An example from the project I’m working on now: it has a class that performs LDAP searches against Active Directory using DirectorySearcher and returns the results as Person objects. My first inclination was to grab the interface for DirectorySearcher and then create a fairly sophisticated stub that I can use for testing. However, that proved problematic because DirectorySearcher doesn’t seem to use an interface and it would require a lot of code to stub it out successfully.
My next thought was to create an Searcher class that internally uses DirectorySearcher, which would let me test the mapping between the LDAP results and the Person object mapping, but that doesn’t gain me very much and it’s yet another level of abstraction.
So I guess the bottom line is this: is there a way structure this so I can do most of my work with unit testing? I’d really rather keep the integration test suite as small as possible, since I have to do the testing against an external data source that keeps changing. I suspect there’s a pattern for doing this, but I haven’t been able to find it.
Thanks!
If you have a class that you can’t dependency inject, then the best pattern would be to create a wrapper object and wrap that object. Then, you can inject your wrapper (or mock of the wrapper) to gain that functionality.
So in your case, you were correct to create a wrapper “Searcher” class that internally calls DirectorySearcher. Whatever methods you need to call on the DirectorySearcher, you provide as virtual methods on your Searcher class. Then you can create a mock searcher class with overriden methods and inject that when unit testing (Or, have Moq create it for you!)