C# unit testing API 2 call -


i have web api 2 web service method. inside i'm using httpcontext.current.request.userhostaddress. when calling controller method directly int unit test isn't filled in errors null object. searched how fill in , found following helped issue: add ip address httprequestmessage

however, needs server name send request to. problem when tests run vsexpress need running api web service, won't when running tests. on top of if seems picks random port run on couldn't hardcode address in above link. how can test api 2 method given above issues?

this line blows when test api method

string ip = httpcontext.current.request.userhostaddress; 

[edit] answer

just knows here solution in code

public class mycontroller : apicontroller {     private: httprequestbase httprequest;      public mycontroller()     {         httprequest = new httprequestwrapper(httpcontext.current.request)     }      public mycontroller(httprequestbase http)     {         httprequest = http;     }      public httpresponsemessage get()     {         string ip = httprequest.userhostaddress;     } } 

i use moq in unit test:

mock<httprequestbase> httprequestmock = new mock<httprequestbase>();  httprequestmock.setup(x => x.userhostaddress).returns("127.0.0.1");  // pass httprequestmock.object controller ctor , go 

replace references httpcontext references httpcontextbase. when in code, initialize httpcontextbase httpcontextwrapper instance, default behavior implementation in web stack.

however in test inject custom httpcontextbase implementation implement methods , behaviors needed test only.

as precised in link:

the httpcontextbase class abstract class contains same members httpcontext class. httpcontextbase class enables create derived classes httpcontext class, can customize , work outside asp.net pipeline. when perform unit testing, typically use derived class implement members customized behavior fulfills scenario testing.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -