c# - How to write integration rest for asp.net web api -
i busy design web service asp.net web api. , want start doing unit tests on each controller.
here test class far:
[testclass] public class mydevicescontrollertest { [testmethod] public void testvaliduser() { mydevicecontroller controller = new mydevicecontroller(); var result = controller.get(); } [testmethod] public void testinvaliduser() { mydevicecontroller controller = new mydevicecontroller(); var result = controller.get(); } }
but web service makes use of token authentication. how need emulate authentication process.
so thinking not maybe make user of http request test it? ie instead of testing controller make http request , check answer?
what easier / better way go testing it?
in asp.net web api, authentication happens in pipeline before controllers invoked, you'll need write integration tests that. walk through how in on-line course on outside-in tdd, here's gist of it:
here's integration test against resource using in-memory http requests. test doesn't use network:
[fact] public void getreturnsresponsewithcorrectstatuscode() { var baseaddress = new uri("http://localhost:8765"); var config = new httpselfhostconfiguration(baseaddress); config.routes.maphttproute( name: "api default", routetemplate: "{controller}/{id}", defaults: new { controller = "home", id = routeparameter.optional }); var server = new httpselfhostserver(config); using (var client = new httpclient(server)) { client.baseaddress = baseaddress; client.defaultrequestheaders.authorization = new authenticationheadervalue( "bearer", new simplewebtoken(new claim("username", "foo")).tostring()); var response = client.getasync("").result; assert.true( response.issuccessstatuscode, "actual status code: " + response.statuscode); } }
as can see, adds "bearer" token http headers of request. simplewebtoken
class custom class wrote occasion, can replace better class creates correct authentication token.
if prefer different authentication scheme (such basic or digest), can set authorization header accordingly.
Comments
Post a Comment