VS Extension & HttpClient : FileNotFoundException

Recently I was working on a Visual Studio Extension which required HttpClient when I ran into the following exception. Frustratingly enough, I wasn’t able to resolve it myself, despite playing around with the versions and using Binding Redirect.

System.IO.FileNotFoundException: ‘Could not load file or assembly ‘System.Net.Http,Version=4.2.0.0, Culture=neutral, ….. The system cannot find the file specified.

The Binding Redirect didn’t quite as it is not possible to use the redirects in VS Extensions. However, the solution turned out to be choosing an alternative for HttpClient as pointed in SOF.

Instead of HttpClient, I had to depend on something which is more native to.Net, like HttpWebRequest. Hope this post is useful to anyone who stumbles on similar issues.

Unit Test for Methods that Call Web API

HttpClient helps you interact with your Rest API’s through its asynchronous methods such as GetAsync. But on a TDD environment, it could become a challenge on how you could write Unit Test cases for a method that invokes the API via GetAsync and ensure that your call successfully invokes the API (considering your API sits in another server and calling it your unit tests would not be ideal). The way I approached this by creating a self hosted API within the Unit Test Project and make the Test Method calls to the API.

The first step was to use Open Web Interface for .Net (or OWIN) to self host an API. Microsoft has put on an extremely useful link for the purpose. Following become by code to configure the API.

 public class WebApiStartup
 {
 // This code configures Web API. The Startup class is specified as a type
 // parameter in the WebApp.Start method.
 public void Configuration(IAppBuilder appBuilder)
 {
 // Configure Web API for self-host. 
 HttpConfiguration config = new HttpConfiguration();
 config.Routes.MapHttpRoute(
 name: "DefaultApi",
 routeTemplate: "api/{controller}/{id}",
 defaults: new { id = RouteParameter.Optional }
 );

 appBuilder.UseWebApi(config);
 }
 }
 The Next Step is go ahead and create the Test Controller, which would be hosting all your api methods.
 [RoutePrefix("api/user")]
public class UserController : ApiController
{
[HttpGet]
[Route("")]
public bool NoParamBooleanResponse()
{
return true;
}
}

Finally, its time to go ahead and write the Test Methods.

 private const string _BaseAddress = "http://localhost:9388/";

[TestMethod]
public async Task CallNoParamAPI_ServerRunning_GetResponseTrue()
{

#region Arrange

var resourceURL = "api/user/SingleParamBooleanResponse";
var restHelper = new RestHelper(_BaseAddress);
bool result;
#endregion

#region Act
using (WebApp.Start<WebApiStartup>(_BaseAddress))
{
result = await restHelper.ExecuteAsync<bool>(resourceURL,HttpMethod.Get);
}
#endregion

#region Assert
Assert.IsTrue(result);
#endregion

}

In the above example, my  restHelper.ExecuteAsync() method invokes the GetAsync Method of HttpClient.