C# Visual Studio 单元测试,模拟客户端 IP 地址 [英] C# Visual Studio Unit Test, Mocking up a client IP address

查看:33
本文介绍了C# Visual Studio 单元测试,模拟客户端 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些单元测试,但在尝试执行以下操作时,我的真实代码抛出了异常:

I am writing some unit tests and I'm getting an exception thrown from my real code when trying to do the following:

string IPaddress = HttpContext.Current.Request.UserHostName.ToString();

有没有办法在不重写我的代码以接受 IP 地址作为参数的情况下模拟 IP 地址?

Is there a way to mock up an IP address without rewriting my code to accept IP address as a parameter?

谢谢!

推荐答案

看看依赖注入.

基本上,您可以通过将数据推送到具有(例如在本例中)上下文"或设置"类的类中来解决此类问题.

Basically you get around such issues by pushing the data into a class with (for example in this case) a "context" or "settings" class.

public interface IAppContext
{
  string GetIP();
}

然后你就有了一个 prod 实现,它在你的测试中做真实的事情和模拟或伪造.

You then have a prod implementation that does the real thing and a mock or fake in you tests.

public class AppContext : IAppConext
{
  public string GetIP()
  {
    return HttpContext.Current.Request.UserHostName.ToString();
  }
}

使用 ip 地址将应用上下文推送到类中...

The app context gets pushed into the class using the ip address...

哦-据我所知,任何 VS 版本都没有内置的模拟,您需要查看众多版本之一 - Rhino 模拟Moq... 有许多!另请参阅 typemock,但它采用了不同的方法.

Oh- and as far as I know there is no inbuilt mocking for any VS editions, you will need to check out one of the many - Rhino mocks, Moq... there are many! Also see typemock but it takes a different approach.

PK :-)

这篇关于C# Visual Studio 单元测试,模拟客户端 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆