简体   繁体   English

C#Factory模式,带抽象和内部构造函数,在单元测试下

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

In my mind is the Microsoft.ServiceBus QueueClient 在我看来是Microsoft.ServiceBus QueueClient

So the QueueClient is abstract class, with an Internal Constructor; 因此QueueClient是抽象类,具有内部构造函数; We call QueueClient.CreateFromConnectionString(...) to get either AMQP or SBMP concrete client class. 我们调用QueueClient.CreateFromConnectionString(...)来获取AMQP或SBMP具体客户端类。 That's the only way to get an instance of QueueClient . 这是获取QueueClient实例的唯一方法。

I can understand why they use this pattern given the ConnectionString specify lots of details. 我可以理解为什么他们使用这种模式,因为ConnectionString指定了很多细节。

But under Unit test, this QueueClient is hard to mock, (at least Moq can't do it); 但是在单元测试下,这个QueueClient很难模拟,(至少Moq不能这样做); 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. 即使使用Microsoft ShimQueueClientShimQueueClient也只是一个包装器,你可以设置一些方法,但你不能新建它或将它作为参数下游传递。

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; 我能想到的东西就像你可以有一个静态方法允许你使用QueueClient.CreateForTest() ,但对此感到奇怪; 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). 或者让这个QueueClient.CreateFromConnectionString接受一个虚拟字符串(我已经通过给它一个非常短的'正确'字符串来做了这QueueClient.CreateFromConnectionString ,你可以在IntelliTrace中看到一些捕获的异常的代价)。

(note: I'm not really asking that one should create your own IQueueClient etc.) (注意:我并不是真的要求创建自己的IQueueClient等)

Thanks a lot. 非常感谢。

Dong

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. 具有内部构造函数的抽象类将实现此接口,使其对伪造,moqing和替换具有灵活性。

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. Microsoft.ServiceBus QueueClient的情况下,我会在生产代码中使用我自己的接口实现来装饰它,这样我就可以在单元测试中伪造装饰器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM