Testing RESTful Methods
by clayshannon
HTML
<h2>I REST My Case</h2>
<p>Although the tip title says "REST methods," and I primarily have ASP.NET Web API REST methods in mind, I reckon this
would work for Web Services, WCF calls, etc. From here on I will just refer to it all as "REST methods," though.</p>
<p>When you call a REST method, you will either get a scalar value, a single JSON "record" (one element from an array), or an
array of JSON "records" or elements.</p>
<p>When testing a local server you have written, you will have a string base that looks something like:
"http://localhost:28642/api/" Otherwise, if you are testing an already-public REST API (your own or somebody else's), it would
be a little different, such as: "http://www.UMustBNuts.com/ToYou/"</p>
<p>This being the case, you can easily set up a couple of general-purpose methods that you can call with whatever makes a
particular REST call differ from another. First, though, add your base URI global to your unit like so:</p>
<pre lang="cs">private const string BASE_URI = "http://localhost:28642/api/";</pre>
<h2>Getting Down to Cases</h2>
<p>You can have one method that returns a single value (like an int, a string, or a JSON element) like this:</p>
<pre lang="cs">
private string GetRESTScalarVal(string uri)
{
var client = new WebClient();
return client.DownloadString(BASE_URI + uri);
}
</pre>
<p>And one that returns an array of JSON objects/elements (that uses JSON.NET) like this:</p>
<h3>Preliminary - Don't Be Wary, It's Not Scary</h3>
<p>To use the following code snippet, you'll need to add JSON.NET (Newtonsoft.Json) to your project and then add "using
Newtonsoft.Json" and "using Newtonsoft.Json.Linq;" to your code unit.</p>
<p>And, you will need to have plopped (technical term first coined by either Rick Monday, Tuesday Weld, Wednesday Addams, Sweet Thursday, Joe Friday, Jeff Saturday, Billy Sunday, or Billie Holliday (I need one! (can't you tell?))) a DataGridView on a...