41799

Owin.TestServer To Test a Middleware that Requires Authentication

Question:

I have a middleware method that requires <em>context.Authentication.User.Identity.Name</em> to be resolved for proper execution. However, when writing a unit test these properties are obviously null as no sign-in has occurred. I am not using Oauth or anything authentication related in this middleware (beyond the obvious name property), as it should be handled elsewhere in another middleware (to promote re-use/flexibility of the component I am developing). Is there a way to mock/fake this value so I can run my test? I have tried everything I can think of to fake a sign-on and I am just stuck at this point. To be clear the middleware needs the value not a webapi call or the like.

//Arrange var resolver = A.Fake<IDependencyResolver>(); A.CallTo(() => resolver.GetService(typeof(ISomeService))).Returns(new TestService()); using (var server = TestServer.Create(app => { app.UseMyMiddleware(new MyMiddlewareOptions() { DependencyResolver = resolver }); app.Run(async ctx => { await ctx.Response.WriteAsync(ctx.Request.Path.Value); }); })) { //Act var response = await server.CreateRequest("/").GetAsync(); //Assert A.CallTo(() => resolver.GetService(typeof(ISomeService))) .MustHaveHappened(Repeated.Exactly.Once); Assert.AreEqual(response.StatusCode, HttpStatusCode.OK); //Etc. }

Answer1:

So here is one way I suppose not thrilled with it but it does the job. I will wait to accept as I imagine there should be a better way.

public class TestFakeLoginMiddleware : OwinMiddleware { public TestFakeLoginMiddleware(OwinMiddleware next) : base(next) { } public override async Task Invoke(IOwinContext context) { var identity = A.Fake<IIdentity>(); A.CallTo(() => identity.Name).Returns("TEST@domain.local"); var user = new ClaimsPrincipal(identity); context.Request.Context.Authentication.User = user; await Next.Invoke(context); } }

Answer2:

A bit late, I know, but could you not just create a new ClaimsIdentity?

public override async Task Invoke(IOwinContext context) { var identity= new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.Name, "TEST@domain.local") }); var user = new ClaimsPrincipal(identity); context.Request.Context.Authentication.User = user; await Next.Invoke(context); }

Recommend

  • NHibernate - join without mapping
  • ADAL js does not work in IE when acquiring token for remote endpoint when website url is added to “T
  • There is any way to trigger a legacy mode for RDTSC?
  • How can I disable automatic filtering in selectize.js? Built-in / plugin / modilfy source?
  • Dynamic JavaScript returned by webapi
  • Web API Routing - No action was found on the controller that matches the request
  • Azure PDF Sharp not using Unicode font
  • Change zIndex in HighChart
  • How to get Fully qualified domain name in unix
  • What is the likely cause of a net::ERR_CONNECTION_ABORTED when uploading a file to Spring
  • Facebook Messenger Platform - Detect user typing
  • How dotnet build chooses the output name
  • AWS-SES: Handling Bounces for Invalid ISPs
  • xtable - background colour of added rows
  • sweetalert2 inputoptions from file in select example
  • How load cv2.KeyPoint and Descriptors correctly on OpenCV 3 with Python 3?
  • How to create CGPath from a SKSpriteNode in SWIFT
  • Symfony 2. CSRF token is invalid
  • Z3: Convert between FP and BitVector?
  • Using a canvas object in a thread to do simple animations - Java
  • uniform generation of points on 3D box
  • What does 'Language neutral' mean with regard to MAKELANGID?
  • Assign variable to the value in HTML
  • Visual Studio 2010 debugger build correctly - compiler pdb and linker pdb not in synch?
  • WPF - CanExecute dosn't fire when raising Commands from a UserControl
  • How to use carriage return with multiple line?
  • How to use remove-erase idiom for removing empty vectors in a vector?
  • How to do unit test for HttpContext.Current.Server.MapPath
  • Highlight one bar in a series in highcharts?
  • Android screen density dpi vs ppi
  • How would I use PHP exceptions to define a redirect?
  • angularjs unit test when to use $rootScope.$new()
  • DirectX11 ClearRenderTargetViewback with transparent buffer?
  • How to extract text from Word files using C#?
  • Perl system calls when running as another user using sudo
  • Change div Background jquery
  • need help with bizarre java.net.HttpURLConnection behavior
  • How does Linux kernel interrupt the application?
  • Busy indicator not showing up in wpf window [duplicate]
  • Why do underscore prefixed variables exist?