Web Api单元测试写法

例如我们在Web Api项目中有个Controller

public class SomeController : ApiController
{
    public HttpResponseMessage Get()
    {
        // 一些操作
        return Request.CreateResponse(HttpStatusCode.OK, someModel);
     }
}

如果你在单元测试中直接调用 SomeController 的Get()方法,那么你将会收到一个Exception提示Request为Null。

因此我们需要在测试代码中构造一个Request,有两种方法

1、简单构造法

[TestMethod]
public void UnitTestMethod()
{
    // 环境准备部分
    YourNameSpace.Controllers.SomeController controller = new SomeController();
    
    // 下面两个语句是构造一个简单的请求报文
    controller.Request = new HttpRequestMessage();
    controller.Request.SetConfiguration(new HttpConfiguration());

    var result = controller.Get();

    // 断言
}

2、可控性更强的构造

[TestMethod]
public void UnitTestMethod()
{
    // 环境准备部分
    YourNameSpace.Controllers.SomeController controller = new SomeController();
    
    var config = new HttpConfiguration();
    var request = new HttpRequestMessage(HttpMethod.Post, "YourUrl");
    var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
    var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "products" } });

    controller.ControllerContext = new HttpControllerContext(config, routeData, request);
    controller.Request = request;
    controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

    var result = controller.Get();

    // 断言
}

然后就可以运行单元测试查看结果了。

posted @ 2014-03-25 11:15  飞鸟_Asuka  阅读(3159)  评论(0编辑  收藏  举报