0

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

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

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

4

1 回答 1

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));
            }
    }

测试客户端代码:

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;
        }
    }
于 2012-05-11T10:04:06.837 回答