Visual Studio 2013でAPIコントローラをテストしようとしています。私のソリューションの1つにWeb APIプロジェクトとテストプロジェクトがあります。私は404を得続けるVisual Studio 2013でHttpClientを使用したユニットテスト/統合テストWeb API
[TestMethod]
public void GetProduct()
{
HttpConfiguration config = new HttpConfiguration();
HttpServer _server = new HttpServer(config);
var client = new HttpClient(_server);
var request = new HttpRequestMessage
{
RequestUri = new Uri("http://localhost:50892/api/product/hello"),
Method = HttpMethod.Get
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var response = client.SendAsync(request).Result)
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
var test = response.Content.ReadAsAsync<CollectionListDTO>().Result;
}
}
:私のテストプロジェクトでは、私はこれでユニットテストを持っています。 Visual Studio(IIS Express)の1つのインスタンスでAPIを実行し、このユニットテストを別のインスタンスでデバッグしようとしました。しかし、運がない。私はブラウザにこのURLを置くことができることを確認しました(1つのVisual Studioがデバッグしているとき)、JSON応答が表示されます。しかし、私はユニットテストとHttpClient
で動作させる方法を理解できません。私は例をオンラインで見つけようとしましたが、見つけられないようです。助けてもらえますか?
更新1: ルートで追加しようとしましたが、何も起こりませんでした。私はHttpServer
オブジェクトなしHttpClient
をアップし、新たな場合、私はそれが仕事を得ることができた :
HttpConfiguration config = new HttpConfiguration();
// Added this line
config.Routes.MapHttpRoute(name: "Default", routeTemplate: "api/product/hello/");
HttpServer _server = new HttpServer(config);
var client = new HttpClient(_server);
[...rest of code is the same]
は、ここに私のAPIコントローラ
[HttpGet]
[Route("api/product/hello/")]
public IHttpActionResult Hello()
{
return Ok();
}
UPDATE解像度です。私はまだVSの2つのインスタンスを実行する必要があります。 1は私のAPIコードを実行し、もう1つは単体テストを実行します。
ここには動作する方法があります。
[TestMethod]
public void Works()
{
var client = new HttpClient(); // no HttpServer
var request = new HttpRequestMessage
{
RequestUri = new Uri("http://localhost:50892/api/product/hello"),
Method = HttpMethod.Get
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var response = client.SendAsync(request).Result)
{
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
}
それはHttpServer
とHttpClient
に渡さHttpConfiguration
では動作しない理由を誰もが知っていますか?私はこれを使用する多くの例を見てきました。 HttpServer
とHttpClient
に渡さHttpConfiguration
と協力して、私はやることができた次の記事を参照
は違いを生むないかもしれませんが、なぜ[GetAsync](https://msdn.microsoft.com/en-us/を使用しませんライブラリ/ hh158944(v = 118).aspx)を直接? –
起動時にOWINパイプラインを使用していますか? 'TestServer'を使う必要があります。 https://blogs.msdn.microsoft.com/webdev/2013/11/26/unit-testing-owin-applications-using-testserver/ – Nkosi
私はowinを使用していません。 – duyn9uyen