简体   繁体   English

单元测试中如何为httprequest usercontrol的Request赋值?

[英]How to assign a value to Request which is of httprequest usercontrol in unit testing?

I have a method which uses the Request.UrlReferrer.Host in the masterpage.asx.cs.我有一个使用 masterpage.asx.cs 中的 Request.UrlReferrer.Host 的方法。

protected string DoSomething()
{
  Request.UrlReferrer.Host is used
//Request is of httprequest usercontrol
}

I am trying to write a unit test case for this method.我正在尝试为此方法编写一个单元测试用例。

and having a call target.DoSomething() but The Request is having null value.并调用 target.DoSomething() 但请求具有 null 值。 How can I give it a value so that the DoSomething() method doesn't break?我怎样才能给它一个值,这样 DoSomething() 方法就不会中断?

Please help.请帮忙。

Thanks.谢谢。

I am going to recommend a different approach, since these values are not settable inside HttpRequest .我将推荐一种不同的方法,因为这些值在HttpRequest中是不可设置的。

Write a class whose sole responsibility is to deal with the HttpRequest and produce the appropriate output. Then extract an interface from that class. DoSomething would then depend upon that interface.编写一个 class,它的唯一职责是处理HttpRequest并生成适当的 output。然后从该 class 中提取一个接口。然后DoSomething将依赖于该接口。 For your test, you would be able to provide a "fake," or a stand-in implementation that can serve data that the method would then use in its logic.对于您的测试,您将能够提供一个“假的”或一个替代实现,它可以提供该方法随后将在其逻辑中使用的数据。

For example, you might have an interface like例如,您可能有一个像这样的界面

interface ICanHandleRequest { }

So you can then have in your production code an implementation that your DoSomething method would normally use.因此,您可以在生产代码中拥有您的 DoSomething 方法通常会使用的实现。

class RequestHandler : ICanHandleRequest { } 

But for your test, you would create a different implementation so that your DoSomething method can be tested.但是对于您的测试,您将创建一个不同的实现,以便可以测试您的 DoSomething 方法。

class TestHandler : ICanHandleRequest { }

You could also use mocking libraries (such as Rhino Mocks , for example) to build such fakes, if you so choose.如果您愿意,也可以使用 mocking 库(例如Rhino Mocks)来构建此类假货。 The idea is that DoSomething doesn't need to know how to use HttpRequest , it has other responsibilities.这个想法是DoSomething不需要知道如何使用HttpRequest ,它有其他职责。 It simply needs the output. In production, that data would come from your real class, and it would use HttpRequest .它只需要 output。在生产中,该数据将来自您的真实 class,并且它将使用HttpRequest For testing, you can simply substitute the implementation with something that can produce data that would be appropriate for your test.对于测试,您可以简单地将实现替换为可以生成适合您的测试的数据的东西。 Make sense?说得通?

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

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