ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – 如何为BadRequest编写单元测试用例?

2019-05-16 10:04:55  阅读:188  来源: 互联网

标签:c unit-testing nunit testcase


我想为下面的代码编写单元测试用例

HomeController.cs

[HttpPost]
        [ActionName("CreateDemo")]
        public async Task<IHttpActionResult> CreateDemo([FromBody] MyRequest request)
        {
            if (request == null)
            {                    
                return BadRequest("request can not be null");
            }
            if (request.MyID == Guid.Empty)
            {
                return BadRequest("MyID must be provided");
            }
        }

我试过跟随哪个不正确的方式我猜是这样的

 [TestMethod]
        public async Task NullCheck()
        {
            try
            {
                var controller = new HomeController();
                var resposne = await controller.CreateDemo(null);
                Assert.AreEqual(); // not sure what to put here
            }
            catch (HttpResponseException ex) //catch is not hit
            {
                Assert.IsTrue(
                     ex.Message.Contains("request can not be null"));
            }

        }

最佳答案:

每个单元测试应测试一个要求或关注点.您的方法实现了两个要求:

1)如果request为null,则返回带有预定义错误消息的BadRequestErrorMessageResult对象.
2)如果请求的MyID属性为空GUID,则返回带有另一个预定义错误消息的BadRequestErrorMessageResult对象.

这意味着我们应该进行两次单元测试:

[Test]
public async Task CreateDemo_returns_BadRequestErrorMessageResult_when_request_is_null()
{
   // Arrange
   var controller = new HomeController();

   // Act
   var response = await controller.CreateDemo(null);

   // Assert
   Assert.IsInstanceOf<BadRequestErrorMessageResult>(response);
   Assert.AreEqual("request can not be null", response.Message);
}

[Test]
public async Task CreateDemo_returns_BadRequestErrorMessageResult_when_request_ID_is_empty_GUID()
{
   // Arrange
   var controller = new HomeController();
   var request = new MyRequest(Guid.Empty);

   // Act
   var response = await controller.CreateDemo(request);

   // Assert
   Assert.IsInstanceOf<BadRequestErrorMessageResult>(response);
   Assert.AreEqual("MyID must be provided", response.Message);
}

您可以更进一步,将每个测试分成两个,其中一个测试返回对象是预期类型,另一个验证返回的对象状态是否符合预期(例如,消息字符串是预期的).这样每次测试就会有一个断言.

附注:

您使用nunit标记标记了此问题,因此我提供了使用该框架的代码.但是,在您的示例中,您使用来自Microsoft单元测试框架的[TestMethod]属性.如果您想使用该框架,您必须进行一些更改,例如用Assert.IsInstanceOfType替换Assert.IsInstanceOf.

我假设GUID通过其构造函数传递给MyRequest,后者将其分配给MyID.

我不是来自网络世界,但我发现BadRequest方法有一个重载,如果将字符串作为参数传递,则返回BadRequestErrorMessageResult.

标签:c,unit-testing,nunit,testcase
来源: https://codeday.me/bug/20190516/1115037.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有