首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟业务层,以便集成测试Web

模拟业务层,以便集成测试Web
EN

Stack Overflow用户
提问于 2014-01-13 20:03:29
回答 1查看 1.1K关注 0票数 4

我想在我的Web上进行集成测试,而不依赖于我的业务层接口。

当运行此操作时:

1)我想模拟_service对象,只需验证它是否被调用

2)我要断言返回了正确的StatusCode

第二个没有问题,但是当我不手动控制/开始创建api控制器时,我如何能够模拟_service对象(ISchoolyearService),因为这是在对控制器进行单元测试时完成的任务。但是我不想单元测试我的API!

代码语言:javascript
复制
 [RoutePrefix("api/schoolyears")]
    public class SchoolyearController : ApiController
    {
        private readonly ISchoolyearService _service;
        public SchoolyearController(ISchoolyearService service)
        {
            _service = service;
        }



 [Route("")]
    [HttpPost]
    public HttpResponseMessage Post([FromBody]SchoolyearCreateRequest request)
    {
        _service.CreateSchoolyear(request);
        return Request.CreateResponse(HttpStatusCode.Created);
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-13 20:36:48

下面是一个简单的示例,说明如何进行内存集成测试。在这里,我使用Unity.WebApi.UnityDependencyResolver注入模拟依赖项。您可以类似地使用任何其他IoC容器。

代码语言:javascript
复制
using Microsoft.Practices.Unity;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using Unity.WebApi;

namespace WebApplication251.Tests.Controllers
{
    [TestClass]
    public class PeopleControllerTest
    {
        string baseAddress = "http://dummyhost/";

        [TestMethod]
        public void PostTest()
        {
            HttpConfiguration config = new HttpConfiguration();

            // use the configuration that the web application has defined
            WebApiConfig.Register(config);

            //override the dependencies with mock ones
            RegisterMockDependencies(config);

            HttpServer server = new HttpServer(config);

            //create a client with a handler which makes sure to exercise the formatters
            HttpClient client = new HttpClient(new InMemoryHttpContentSerializationHandler(server));

            SchoolyearCreateRequest req = new SchoolyearCreateRequest();

            using (HttpResponseMessage response = client.PostAsJsonAsync<SchoolyearCreateRequest>(baseAddress + "api/schoolyears", req).Result)
            {
                Assert.IsNotNull(response.Content);
                Assert.IsNotNull(response.Content.Headers.ContentType);
                Assert.AreEqual<string>("application/json; charset=utf-8", response.Content.Headers.ContentType.ToString());

                SchoolyearCreateRequest recSCR = response.Content.ReadAsAsync<SchoolyearCreateRequest>().Result;

                //todo: verify data
            }
        }

        private void RegisterMockDependencies(HttpConfiguration config)
        {
            var unity = new UnityContainer();

            unity.RegisterType<ISchoolyearService, MockSchoolyearService>();

            config.DependencyResolver = new UnityDependencyResolver(unity);
        }
    }

    [RoutePrefix("api/schoolyears")]
    public class SchoolyearController : ApiController
    {
        private readonly ISchoolyearService _service;
        public SchoolyearController(ISchoolyearService service)
        {
            _service = service;
        }

        [Route]
        [HttpPost]
        public HttpResponseMessage Post([FromBody]SchoolyearCreateRequest request)
        {
            _service.CreateSchoolyear(request);
            return Request.CreateResponse(HttpStatusCode.Created);
        }
    }

    public class InMemoryHttpContentSerializationHandler : DelegatingHandler
    {
        public InMemoryHttpContentSerializationHandler(HttpMessageHandler innerHandler)
            : base(innerHandler)
        {
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Content = await ConvertToStreamContentAsync(request.Content);

            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

            response.Content = await ConvertToStreamContentAsync(response.Content);

            return response;
        }

        private async Task<StreamContent> ConvertToStreamContentAsync(HttpContent originalContent)
        {
            if (originalContent == null)
            {
                return null;
            }

            StreamContent streamContent = originalContent as StreamContent;

            if (streamContent != null)
            {
                return streamContent;
            }

            MemoryStream ms = new MemoryStream();

            await originalContent.CopyToAsync(ms);

            // Reset the stream position back to 0 as in the previous CopyToAsync() call,
            // a formatter for example, could have made the position to be at the end
            ms.Position = 0;

            streamContent = new StreamContent(ms);

            // copy headers from the original content
            foreach (KeyValuePair<string, IEnumerable<string>> header in originalContent.Headers)
            {
                streamContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            return streamContent;
        }
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21100336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档