Search code examples
c#.netunit-testingnunitfakeiteasy

Unable to create fake of request.Uri


I have a chunk of code that I want to test:

 public override async Task Invoke(IOwinContext context)
 {
 
   if (context.Request.Uri.AbsolutePath.ToLower().Equals("/data"))
   {
     ..other stuff
   }
    await this.Next.Invoke(context);
 }

Now I want to unit test this but getting an exception for AbsolutePath

System.InvalidOperationException : This operation is not supported for a relative URI. at System.Uri.get_AbsolutePath()

Here is my unit test:

   [Test]
   public void MiddleWare_Should_Not_Call_Process_Request_IF_Uri_Does_Not_Match()
   {
     var request = A.Fake<IOwinRequest>();
     A.CallTo(() => request.Uri).Returns(new Uri("http://dummyUrl.com/login"));
     var middleware = new MyMiddleware(_owinMiddleware);
     middleware.Invoke(this._owinContext).GetAwaiter().GetResult();

     Assert.IsNull(this._owinContext.Response);
  }

I am using Nuit and FakeItEast. Any idea how can I fix this?


Solution

  • You should be mocking IOwinContext.Request too. Otherwise it will not be able to resolve the request itself and therefore the mock request will never be used.

       [Test]
       public void MiddleWare_Should_Not_Call_Process_Request_IF_Uri_Does_Not_Match()
       {
         var request = A.Fake<IOwinRequest>();
         A.CallTo(() => this._owinContext.Request).Returns(request); 
         A.CallTo(() => request.Uri).Returns(new Uri("http://dummyUrl.com/login"));
         var middleware = new MyMiddleware(_owinMiddleware);
         middleware.Invoke(this._owinContext).GetAwaiter().GetResult();
    
         Assert.IsNull(this._owinContext.Response);
      }