本文介绍了如何使用Moq模拟NamespaceManager类的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想模拟CreateTopicAsync方法.但是由于班级的封闭性,我无法模拟班级.有人知道吗?

I want to mock CreateTopicAsync method. But because of the sealed nature of the class i am not able to mock the class.Any one Knows?

推荐答案

您不能模拟sealed类.模拟依赖于继承来构建数据的实时副本.因此,尝试模拟sealed类是不可能的.

You can't mock a sealed class. Mocking relies on inheritence to build on the fly copies of the data. So trying to mock a sealed class is impossible.

您可以做的是写一个包装器:

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....
}

模拟界面

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);

不幸的是,这是您可以做的最好的事情.这是 HttpContextWrapper

Unfortunatly that's the best you can do. It's a siliar implementation to HttpContextWrapper

这篇关于如何使用Moq模拟NamespaceManager类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:36