简体   繁体   English

C#Visual Studio单元测试,模拟客户端IP地址

[英]C# Visual Studio Unit Test, Mocking up a client IP address

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

Is there a way to mock up an IP address without rewriting my code to accept IP address as a parameter? 有没有一种方法可以模拟IP地址而无需重写我的代码以接受IP地址作为参数?

Thanks! 谢谢!

Take a look at Dependency Injection . 看一看依赖注入

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

You then have a prod implementation that does the real thing and a mock or fake in you tests. 然后,您将获得一个执行实物的prod实现,并在测试中进行模拟或伪造。

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

The app context gets pushed into the class using the ip address... 使用ip地址将应用上下文推送到类中...

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! 哦,据我所知,任何VS版本都没有内置的模拟功能,您将需要检查其中一种-Rhino 模拟功能Moq ...有很多! Also see typemock but it takes a different approach. 另请参阅typemock,但采用不同的方法。

PK :-) PK :-)

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

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