Skip to content

Allows to fake HttpContext.Current for unit testing purposes

License

Notifications You must be signed in to change notification settings

gswartz777/FakeHttpContext

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

69 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FakeHttpContext

# Build status

This util allows to initialize HttpContex.Current with fake context.

Install with NuGet

You can install the utility with NuGet

Examples

[Fact]
public void Should_initialize_HttpContext_Current()
{
  // Arrange
  using (new FakeHttpContext())
  {
    // Assert
    HttpContext.Current.Should().NotBeNull();
  }
}

[Fact]
public void Should_fake_user_agent()
{
  // Arrange
  const string ExpectedUserAgentString = "user agent string";
  using (new FakeHttpContext {UserAgent = ExpectedUserAgentString})
  {
    // Assert
    HttpContext.Current.Request.UserAgent.Should().Be(ExpectedUserAgentString);
  }
}

[Fact]
public void Should_allow_to_use_map_path()
{
  // Arrange
  var expectedPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "myPath");

  // Act
  using (new FakeHttpContext())
  {
  // Assert
    HttpContext.Current.Server.MapPath("myPath").Should().Be(expectedPath);
  }
}

[Theory, AutoData]
public void Should_be_possible_to_fake_http_headers(string headerKey, string headerValue)
{
    // Act
    using (new FakeHttpContext { Request = { { headerKey, headerValue } } })
    {
        // Assert
        HttpContext.Current.Request.Headers[headerKey].Should().Be(headerValue);
    }
}

[Theory, AutoData]
public void Should_be_possible_to_fake_post_request(string postData){
  // Arrange
    using (var context = new FakeHttpContext
    {
        // Act
        Request =
        {
            PostData = new FakePostData(postData, System.Text.Encoding.UTF32)
        }
    })
    {
        HttpContext.Current.Request.InputStream.Seek(0, SeekOrigin.Begin);
        using (var reader = new StreamReader(HttpContext.Current.Request.InputStream, System.Text.Encoding.UTF32))
        {
            var actualData = reader.ReadToEnd();

            // Assert
            actualData.Should().Be(postData);
            HttpContext.Current.Request.ContentEncoding.Should().Be(System.Text.Encoding.UTF32);
        }
    }
}

For more examples please see FakeHttpContext.Tests project.
Great tool AutoFixture is used in the test and examples, you definitely should try it, if you haven't yet :thumbsup:!

About

Allows to fake HttpContext.Current for unit testing purposes

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C# 95.4%
  • PowerShell 4.6%