且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

存根或模拟ASP.NET Web API HttpClient

更新时间:2023-02-15 21:02:13

我使用Moq,可以存根HttpClient.我认为Rhino Mock也是一样(我自己没有尝试过). 如果只想对HttpClient存根,则下面的代码应该可以工作:

I use Moq and I can stub out the HttpClient. I think this the same for Rhino Mock (I haven’t tried by myself). If you just want to stub the HttpClient the below code should work:

var stubHttpClient = new Mock<HttpClient>();
ValuesController controller = new ValuesController(stubHttpClient.Object);

如果我错了,请纠正我.我猜您在这里指的是在HttpClient中存根成员.

Please correct me if I’m wrong. I guess you are referring to here is that stubbing out members within HttpClient.

大多数流行的隔离/模拟对象框架不允许您对非虚拟成员进行存根/设置 例如,下面的代码引发异常

Most popular isolation/mock object frameworks won’t allow you to stub/setup on non- virtual members For example the below code throws an exception

stubHttpClient.Setup(x => x.BaseAddress).Returns(new Uri("some_uri");

您还提到要避免创建包装器,因为您将包装许多HttpClient成员.不清楚为什么需要包装许多方法,但是您可以轻松地仅包装所需的方法.

You also mentioned that you would like to avoid creating a wrapper because you would wrap lot of HttpClient members. Not clear why you need to wrap lots of methods but you can easily wrap only the methods you need.

例如:

public interface IHttpClientWrapper  {   Uri BaseAddress { get;  }     }

public class HttpClientWrapper : IHttpClientWrapper
{
   readonly HttpClient client;

   public HttpClientWrapper()   {
       client = new HttpClient();
   }

   public Uri BaseAddress   {
       get
       {
           return client.BaseAddress;
       }
   }
}

我认为可能对您有所帮助的其他选项(这里有很多示例,因此我不会编写代码) Microsoft Moles框架 http://research.microsoft.com/en-us/projects/moles/一个> Microsoft伪造品:(如果使用的是VS2012 Ultimate) http://msdn.microsoft.com/en-us/library/hh549175.aspx

The other options that I think might benefit for you (plenty of examples out there so I won’t write the code) Microsoft Moles Framework http://research.microsoft.com/en-us/projects/moles/ Microsoft Fakes: (if you are using VS2012 Ultimate) http://msdn.microsoft.com/en-us/library/hh549175.aspx