Search code examples
c#unit-testingabstract-classfactory-patterninternal

C# Factory pattern with Abstract and Internal Constructor, under Unit test


In my mind is the Microsoft.ServiceBus QueueClient

So the QueueClient is abstract class, with an Internal Constructor; We call QueueClient.CreateFromConnectionString(...) to get either AMQP or SBMP concrete client class. That's the only way to get an instance of QueueClient.

I can understand why they use this pattern given the ConnectionString specify lots of details.

But under Unit test, this QueueClient is hard to mock, (at least Moq can't do it); even with Microsoft Fakes, the ShimQueueClient is only a wrapper with some methods you can setup, but you can't new it or pass it as parameter downstream.

My question is when you decided to use this kind of Pattern for whatever reason, what can you do to make it more friendly to tests?

Something I can think of like you can have a static method allow you to QueueClient.CreateForTest(), but feel weird about this; or make this QueueClient.CreateFromConnectionString to take dummy string (which I already did by give it a very short 'correct' string, with the cost of some catched exceptions you can see within IntelliTrace).

(note: I'm not really asking that one should create your own IQueueClient etc.)

Thanks a lot.

Dong


Solution

  • I suggest you create a base interface to back this pattern. Your abstract class with internal constructor would implement this interface, making it flexible for faking, moqing and substitution.

    In the case of Microsoft.ServiceBus QueueClient, I would decorate it with my own interface implementation in production code so that i can fake the decorator in the unit tests.