Last active
April 26, 2016 14:28
-
-
Save cscorley/088b14901997b0f8ab059d75bc2cc3b9 to your computer and use it in GitHub Desktop.
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
private IDisposable _shimContext { get; set; } | |
/// <summary> | |
/// <para>Rules for evaluating expected HTTP requests under test.</para> | |
/// <para>When a rule is matched, the shim will be set up with the information contained in the tuple: the raw HTTP return code and response string.</para> | |
/// <para>Each rule is a function and is given the original Uri of the request and, as a convenience, the parsed query portion of the HTTP request. | |
/// The functions are expected to return a boolean value of whether the parameters match.</para> | |
/// </summary> | |
protected Dictionary<Func<Uri, NameValueCollection, bool>, Tuple<HttpStatusCode, string>> expectedHttpRequests; | |
[TestInitialize] | |
public void Setup() | |
{ | |
_testobject = new Some(); | |
_shimContext = ShimsContext.Create(); | |
ShimBehaviors.BehaveAsDefaultValue(); | |
expectedHttpRequests = new Dictionary<Func<Uri, NameValueCollection, bool>, Tuple<HttpStatusCode, string>>(); | |
ShimHttpWebRequest.AllInstances.GetResponse = (request) => | |
{ | |
var responseShim = new ShimHttpWebResponse(); | |
var parts = HttpUtility.ParseQueryString(request.RequestUri.Query); | |
foreach (var condition in expectedHttpRequests) | |
{ | |
if (condition.Key(request.RequestUri, parts)) | |
{ | |
responseShim.StatusCodeGet = () => condition.Value.Item1; | |
responseShim.GetResponseStream = () => new MemoryStream(Encoding.UTF8.GetBytes(condition.Value.Item2)); | |
return responseShim.Instance; | |
} | |
} | |
Assert.Fail("Got unexpected Request URL: {0}", request.RequestUri.ToString()); // shouldn't end up here :| | |
return null; | |
}; | |
} | |
[TestCleanup] | |
public void Teardown() | |
{ | |
_shimContext.Dispose(); | |
_shimContext = null; | |
} | |
[TestMethod, TestCategory("Unit")] | |
public void TestRules() | |
{ | |
expectedHttpRequests.Add( | |
(uri, query) => uri.AbsolutePath == "/user" && query["id"] == 5, | |
Tuple.Create( | |
HttpStatusCode.OK, | |
"{\"id\": 5,\"status\":\"bonehead\"}" | |
)); | |
var user = _testobject.GetUser(5) | |
Assert.AreEqual("bonehead", user.Status) | |
Assert.AreEqual(5, user.id) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment