-
-
Save kkolodziejczak/77ea97ec70442b7591d5b402d9bbb185 to your computer and use it in GitHub Desktop.
In memory http server for C# unit and integration tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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