2014-04-25 4 views
3

저는 자체 호스트 서버와 함께 HTTP 클라이언트/서버 기능 테스트를 포함하는 단위 테스트 세트를 작업 중입니다. 그러나 나는 심지어 가장 간단한 테스트를받을 수 없습니다.HTTP 자체 호스팅 및 유닛 테스트

 Actual status code: NotFound 
     Expected: True 
     But was: False 
: 여기 내 코드

UnitTest1.cs

using System; 
    using System.Net.Http; 
    using System.Web.Http.SelfHost; 
    using NUnit.Framework; 
    using SomeWebService; 

    namespace UnitTestProject1 
    { 
     [TestFixture] 
     public class UnitTest1 
     { 
      [Test] 
      public void TestMethod1() 
      { 
       var baseAddress = new Uri("http://localhost:9876"); 
       var config = new HttpSelfHostConfiguration(baseAddress); 
       new Bootstrap().Configure(config); 
       var server = new HttpSelfHostServer(config); 
       using (var client = new HttpClient(server)) 
       { 
        client.BaseAddress = baseAddress; 
        var response = client.GetAsync("").Result; 
        Assert.True(response.IsSuccessStatusCode, "Actual status code: " + response.StatusCode); 
       } 
      } 
     } 
    } 

using System.Web.Http; 

    namespace SomeWebService 
    { 
     public class Bootstrap 
     { 
      public void Configure(HttpConfiguration config) 
      { 
       config.Routes.MapHttpRoute(name: "API Default", routeTemplate: "{controller}/{id}", defaults: new 
       { 
        controller = "Home", 
        id = RouteParameter.Optional 
       }); 
      } 
     } 
    } 

Bootstrap.cs

과 HomeController.cs

using System.Net.Http; 
    using System.Web.Http; 

    namespace SomeWebService 
    { 
     class HomeController:ApiController 
     { 
      public HttpResponseMessage Get() 
      { 
       return this.Request.CreateResponse(); 
      } 
     } 
    } 

테스트 결과입니다

내가 뭘 잘못하고 있니?

패키지는 명시 적으로 public으로 선언하지 않았기 때문에

Install-Package Microsoft.Net.Http -version 2.0.20710 
Install-Package Microsoft.AspNet.WebApi.SelfHost -version 4.0.20918 
Install-Package Microsoft.AspNet.WebApi.Core -version 4.0.20710 

답변

1

HomeController는 개인입니다 설치되어 있어야합니다. 그것은 공공 만드는 시도 :

당신이 당신의 테스트가 더 빨리 실행하려면
public class HomeController:ApiController 
{ 
    public HttpResponseMessage Get() 
    { 
     return this.Request.CreateResponse(); 
    } 
} 
+0

천재를 전체 TCP/IP 스택을 피할 수 ... 고마워, 마크. – Darek

2

, 당신은 순수하게 메모리 호스트를 사용하여

 [Test] 
     public void TestMethod1() 
     { 
      var config = new HttpConfiguration(); 
      new Bootstrap().Configure(config); 
      var server = new HttpServer(config); 
      using (var client = new HttpClient(server)) 
      { 
       client.BaseAddress = baseAddress; 
       var response = client.GetAsync("").Result; 
       Assert.True(response.IsSuccessStatusCode, "Actual status code: " + response.StatusCode); 
      } 
     }