Scotch is an HTTP recorder and playback library. What this means is that, whether we’re writing unit tests which require an HTTP connection or content, or if we need to test and application offline, we can first record a session, running code against our HttpClient and record the results of any calls, then take our application offline and replay those interactions.
Let’s get started…
Add the NuGet package scotch. If you’re using C# this will also deploy some F# assemblies, don’t panic, as it’s .NET it’s runnable from C# and luckily the API uses C# design style and hence looks like any other C#/.NET framework library.
This example, shows how we might have code which connects to the scotch GitHub page and using ScotchMoe.Recording, we record any interactios to the httpClient and save these to the data.json file – this example shows using the HttpClients.NewHttpClientWithHandler if we need to go through a proxy server, otherwise we just use HttpClients.NewHttpClient
var proxy = new WebProxy(proxy, port) { Credentials = CredentialCache.DefaultCredentials }; var httpHandler = new HttpClientHandler { Proxy = proxy }; var httpClient = HttpClients.NewHttpClientWithHandler( httpHandler, @"c:\Development\interactions\data.json", ScotchMode.Recording); var result = await httpClient.GetAsync( new Uri("https://github.com/mleech/scotch"));
Now, assuming we’ve saved a recording we can switch the code to ScotchMode.Replaying (this example demonstrates non-proxy code and hence uses HttpClients.NewHttpClient
var httpClient = HttpClients.NewHttpClient( @"c:\Development\interactions\data.json", ScotchMode.Replaying); var result = await httpClient.GetAsync( new Uri("https://github.com/mleech/scotch"));