2012-05-03 18 views
0

ASP.NET Web API getting started tutorialsのいずれかで、テストプロジェクトを追加するオプションが無効になっていることがわかりましたが、その理由はわかりません。他のMVCプロジェクトと同じようにASP.NET Web APIプロジェクトをテストするだけですか?ASP.NET Web APIプロジェクトのテストを書く

私は何かプロトタイプを作成しています。私は怠け者で、MVCプロジェクトを使用していくつかのコントローラからJSONを返してWebサービスをモックアップしています。物事がもう少し深刻になるにつれ、私は物事を「より正確に」始める必要があります。

ASP.NET Web APIプロジェクトのテストを作成するにはどうすればよいですか、より広義には、実際のWebサービスのテストを自動化するにはどうすればよいですか?

答えて

0

私はそうのようにこれを行っています

[TestFixture] 
    public class CountriesApiTests 
    { 
     private const string BaseEndPoint = "http://x/api/countries"; 

     [Test] 
      public void Test_CountryApiController_ReturnsListOfEntities_ForGet() 
      { 
       var repoMock = new Mock<ISimpleRepo<Country>>(); 

       ObjectFactory.Initialize(x => x.For<ISimpleRepo<Country>>().Use(repoMock.Object)); 
       repoMock.Setup(x => x.GetAll()).Returns(new List<Country> 
                      { 
                       new Country {Name = "UK"}, 
                       new Country {Name = "US"} 
                      }.AsQueryable); 

       var client = new TestClient(BaseEndPoint); 
       var countries = client.Get<IEnumerable<CountryModel>>(); 
       Assert.That(countries.Count(), Is.EqualTo(2)); 
      } 
    } 

TestClientコード:

public class TestClient 
    { 
     protected readonly HttpClient _httpClient; 
     protected readonly string _endpoint; 

     public HttpStatusCode LastStatusCode { get; set; } 

     public TestClient(string endpoint) 
     { 
      _endpoint = endpoint; 

      var config = new HttpConfiguration(); 
      config.ServiceResolver.SetResolver(new WebApiDependencyResolver()); 
      config.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { id = RouteParameter.Optional });         

      _httpClient = new HttpClient(new HttpServer(config));    
     }  

     public T Get<T>() where T : class 
     { 
      var response = _httpClient.GetAsync(_endpoint).Result; 
      response.EnsureSuccessStatusCode(); // need this to throw exception to unit test 

      return response.Content.ReadAsAsync<T>().Result; 
     } 
    } 
関連する問題