简体   繁体   中英

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.

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. How can I give it a value so that the DoSomething() method doesn't break?

Please help.

Thanks.

I am going to recommend a different approach, since these values are not settable inside 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. 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.

class RequestHandler : ICanHandleRequest { } 

But for your test, you would create a different implementation so that your DoSomething method can be tested.

class TestHandler : ICanHandleRequest { }

You could also use mocking libraries (such as Rhino Mocks , for example) to build such fakes, if you so choose. The idea is that DoSomething doesn't need to know how to use HttpRequest , it has other responsibilities. It simply needs the output. In production, that data would come from your real class, and it would use HttpRequest . For testing, you can simply substitute the implementation with something that can produce data that would be appropriate for your test. Make sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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