简体   繁体   English

如何使用Moq模拟NamespaceManager类的方法?

[英]How to Mock NamespaceManager Class Methods Using Moq?

https://docs.microsoft.com/en-us/dotnet/api/microsoft.servicebus.namespacemanager?redirectedfrom=MSDN#microsoft_servicebus_namespacemanager https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.servicebus.namespacemanager?redirectedfrom=MSDN#microsoft_servicebus_namespacemanager

I want to mock CreateTopicAsync method. 我想模拟CreateTopicAsync方法。 But because of the sealed nature of the class i am not able to mock the class. 但是由于班级的封闭性,我无法模拟班级。 Any one Knows? 有谁知道?

You can't mock a sealed class. 您不能嘲笑sealed类。 Mocking relies on inheritence to build on the fly copies of the data. 模拟依赖于继承来构建数据的实时副本。 So trying to mock a sealed class is impossible. 因此,尝试模拟sealed类是不可能的。

So what do I do? 那我该怎么办?

What you can do is write a wrapper: 您可以做的是编写一个包装器:

public class NamespaceManagerWrapper : INamespaceManagerWrapper 
{
   private NamespaceManager _instance;

   public NamespaceManagerWrapper(NamespaceManager instance)
   {
      _instance = instance;
   }

   public ConsumerGroupDescription CreateConsumerGroup(ConsumerGroupDescription description)
   {
       return _instace.CreateConsumerGroup(description);
   }

   etc....
}

interface for the mock 模拟界面

public interface INamespaceManagerWrapper
{
   ConsumerGroupDescription CreateConsumerGroup(ConsumerGroupDescription description);
   ....etc.
}

your method should now accept your wrapper interface on the original object: 您的方法现在应该在原始对象上接受包装器接口:

public void myMethod(INamespaceManagerWrapper mockableObj)
{
   ...
   mockableObj.CreateConsumerGroup(description);
   ...
}

Now you can mock the interface: 现在您可以模拟界面:

Mock<INamespaceManagerWrapper> namespaceManager = new Mock<INamespaceManagerWrapper>();
....etc.

myObj.myMethod(namespaceManager.Object);

Unfortunatly that's the best you can do. 不幸的是,这是您可以做的最好的事情。 It's a siliar implementation to HttpContextWrapper 这是HttpContextWrapper的辅助实现

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

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