编写ASP.NET Web API项目的测试

时间:2012-05-03 00:48:04

标签: asp.net web-services unit-testing asp.net-web-api

我在其中一个ASP.NET Web API getting started tutorials中注意到添加测试项目的选项已被禁用,我不确定为什么会这样。我会像其他任何MVC项目一样测试ASP.NET Web API项目吗?

我正在进行原型设计并且我很懒,只是使用MVC项目并从一些控制器返回JSON来模拟Web服务。随着事情开始变得更加严重,我需要开始“更正确”地做事。

那么我应该如何为ASP.NET Web API项目编写测试呢?更广泛地说,我如何自动测试实际的Web服务呢?

1 个答案:

答案 0 :(得分: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;
        }
    }