How to write unit test for BadRequest?

I want to write Unit test cases for the following code

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

I tried as it should, which is not the way I guess

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

        }
+4
source share
1 answer

Each unit test should check one requirement or problem. Your method implements two requirements:

1) If prompted null, return BadRequestErrorMessageResultan object with a predefined error message. 2) If the request property is MyIDempty GUID, return an object BadRequestErrorMessageResultwith another predefined error message.

This means that we must have two unit tests:

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

, , , , , (, Message ). , .

:

nunit, , . , , [TestMethod], Microsoft. , , . Assert.IsInstanceOf Assert.IsInstanceOfType.

, GUID MyRequest , MyID.

, , BadRequest , BadRequestErrorMessageResult, string .

+4

Source: https://habr.com/ru/post/1652282/


All Articles