Web Api单元测试写法

news/2024/7/8 17:34:06

例如我们在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();
// 断言
}

  


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


http://lihuaxi.xjx100.cn/news/248451.html

相关文章

Android:ViewPager为页卡内视图组件添加事件

在数据适配器PagerAdapter的初始化方法中添加按钮事件&#xff0c;这里是关键&#xff0c;首先判断当前的页卡编号。必须使用当前的view来获取按钮。 Overridepublic Object instantiateItem(View arg0, int arg1) {if (arg1 < 3) {((ViewPager) arg0).addView(mListViews.g…

单目标优化,多目标优化,数值优化,组合优化

何为优化&#xff1f;措施&#xff1a; 对应方法 变得更优&#xff1a; 对应的结果更加的好 优化&#xff1a; 动词&#xff0c;一种行为方法----------->目的是获得更好的结果&#xff0c;总之有所改善 优化问题的三要素&#xff1a; &#xff08;1) 决策变量 所变&…

Eigen使用笔记

1. 常用头文件 2. 使用问题汇总 2.1. 求逆 在有的环境下&#xff0c;有的版本的Eigen&#xff0c;使用Eigen的inverse()求逆&#xff0c;和正确值差一个负号&#xff0c;这是Eigen中存在的bug&#xff0c;修改为矩阵分解后该问题就能解决 Eigen::Matrix4d I Eigen::Matrix4…

单件类的安全实现

1. 不安全的实现方法 std::unique_ptr<Interface> instance_(nullptr);static Interface* GetInstance() {if (instance_.get() nullptr) {instance_.reset(new Interface());}return instance_.get(); } instance_.reset(new Interface)包含了三步&#xff1a; 1&am…

spring cloud快速搭建

为什么80%的码农都做不了架构师&#xff1f;>>> 一&#xff1a;注册中心 服务提供者&#xff08;简单&#xff09; 注册中心本身就可以是服务提供者&#xff0c;如果有需求可以分开。 1&#xff1a;pom.xml <?xml version"1.0" encoding"UTF-8…

测试找人

2019独角兽企业重金招聘Python工程师标准>>> tomcat 测试找人 转载于:https://my.oschina.net/zhouyuan/blog/125854

郭光灿院士--奇妙的量子世界笔记1(量子世界和经典世界区联系)

视频来源&#xff1a; 网易公开课 图片来源&#xff1a;视频中截图 声明&#xff1a;视频只看了一遍&#xff0c;不求甚解&#xff0c;一些地方难免出错还望指正 1. 为什么神奇&#xff1f; 这个神奇是对比经典世界&#xff08;特点就是确定性&#xff09;&#xff0c;显示出来…

T-SQL WITH 分号问题

使用with 前面有sql语句时候 运行 with tempTbale(id) as ( select ..... )select * from tempTbale 运行上面语句 提示下面错误 Incorrect syntax near the keyword with. If this statement is a common table expression, an xmlnamespaces clause or a change tracking con…