Skip to content

Instantly share code, notes, and snippets.

@isidore
Last active August 29, 2015 14:02
Show Gist options
  • Save isidore/660781fd7b5c244115eb to your computer and use it in GitHub Desktop.
Save isidore/660781fd7b5c244115eb to your computer and use it in GitHub Desktop.
Executable Query Test of a Rest call
using System;
using System.Net.Http;
using System.Threading.Tasks;
using ApprovalTests;
using ApprovalTests.Reporters;
using ApprovalUtilities.Persistence;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ObjectApproval;
/**
* This code requires the following Nuget Packages
* ApprovalTests
* ObjectApprovals
* Microsoft HTTP Client libraries
**/
namespace AdvancedUnitTesting
{
[TestClass]
[UseReporter(typeof (DiffReporter))]
public class RestCallTests
{
[TestMethod]
public void TestGoogleQuery()
{
Approvals.Verify(new GoogleQuery("lolcats"));
}
}
public class GoogleQuery : RestQuery<GoogleQueryResults>
{
private readonly string searchTerm;
public GoogleQuery(String searchTerm)
{
this.searchTerm = searchTerm;
}
public override string GetQuery()
{
return string.Format("?v=1.0&q={0}", searchTerm);
}
public override string GetBaseAddress()
{
return "http://ajax.googleapis.com/ajax/services/search/web";
}
public override GoogleQueryResults Load()
{
return new GoogleQueryResults(GetResponse().Result);
}
}
public class GoogleQueryResults
{
public GoogleQueryResults(HttpResponseMessage result)
{
//do extraction stuff
}
}
public abstract class RestQuery<T> : IExecutableQuery, ILoader<T>
{
public abstract string GetQuery();
public abstract string GetBaseAddress();
public string ExecuteQuery(string query)
{
var json = ExecuteAsync(query).Result.Content.ReadAsStringAsync().Result;
return JsonPrettyPrint.FormatJson(json);
}
public Task<HttpResponseMessage> ExecuteAsync(string requestUri)
{
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(GetBaseAddress());
return httpClient.GetAsync(requestUri);
}
public Task<HttpResponseMessage> GetResponse()
{
return ExecuteAsync(GetQuery());
}
public abstract T Load();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment