How to access HttpContext inside a unit test in ASP.NET 5 / MVC 6 -
lets setting value on http context in middleware. example httpcontext.user.
how can test http context in unit test. here example of trying
middleware
public class myauthmiddleware { private readonly requestdelegate _next; public myauthmiddleware(requestdelegate next) { _next = next; } public async task invoke(httpcontext context) { context.user = setuser(); await next(context); } }
test
[fact] public async task usershouldbeauthenticated() { var server = testserver.create((app) => { app.usemiddleware<myauthmiddleware>(); }); using(server) { var response = await server.createclient().getasync("/"); // after calling middleware want assert // user in httpcontext set correctly // how can access httpcontext here? } }
following 2 approaches use:
// directly test middleware without setting pipeline [fact] public async task approach1() { // arrange var httpcontext = new defaulthttpcontext(); var authmiddleware = new myauthmiddleware(next: (innerhttpcontext) => task.fromresult(0)); // act await authmiddleware.invoke(httpcontext); // assert // note user property on defaulthttpcontext never null , // specific checks contents of principal (ex: claims) assert.notnull(httpcontext.user); var claims = httpcontext.user.claims; //todo: verify claims } [fact] public async task approach2() { // arrange var server = testserver.create((app) => { app.usemiddleware<myauthmiddleware>(); app.run(async (httpcontext) => { if(httpcontext.user != null) { await httpcontext.response.writeasync("claims: " + string.join( ",", httpcontext.user.claims.select(claim => string.format("{0}:{1}", claim.type, claim.value)))); } }); }); using (server) { // act var response = await server.createclient().getasync("/"); // assert var actual = await response.content.readasstringasync(); assert.equal("claims: claimtype1:claimtype1-value", actual); } }
Comments
Post a Comment