Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Markus-Ende/057b5cd7b929f112b30ab84e951f2452 to your computer and use it in GitHub Desktop.
Save Markus-Ende/057b5cd7b929f112b30ab84e951f2452 to your computer and use it in GitHub Desktop.
In memory http server for C# unit and integration tests
public static Task BasicHttpServer(string url, string outputHtml)
{
return Task.Run(() =>
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();
// GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerResponse response = context.Response;
Stream stream = response.OutputStream;
var writer = new StreamWriter(stream);
writer.Write(outputHtml);
writer.Close();
});
}
//
// Example
//
[Test]
public void should_return_html()
{
// Arrange
string url = GetLocalhostAddress();
using(BasicHttpServer(url, "some html"))
{
var myhttpclient = new MyHttpClient(new Uri(url));
// Act
string actualContent = myhttpclient.Read();
// Assert
Assert.That(actualContent, Does.Contain("some html"));
}
}
private string GetLocalhostAddress()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return $"http://localhost:{port}/";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment