How do I write a unit test for checking a bad request in a conditional statement in C# ASP.NET?

Viewed 375

I have a controller with a simple conditional statement that checks a value and then returns a BadRequest should that value not match what is expected.

public async Task<IActionResult> SendCarDetails(string carValue)
{
    try
    {
        if (carValue== "0")
        {
            return BadRequest("Car value cannot be 0");
        }
    }
    catch (Exception ex)
    {
        return StatusCode(500);
    }
}

To test this simple condition I wrote a unit test, although it works I feel that it's a little disconnected from the above method and therefore is not sufficient to qualify as a test. This defines the value as being 0 and then checks it, I then create a new BadRequestResult and should that response match 400 then the test is passed.

[TestMethod]
public void SendCarDetails_Returns_400_When_Zero()
{
    string paymentValue = "0";

    if (paymentValue == "0") 
    {
        var response = new BadRequestResult();
        Assert.AreEqual(StatusCodes.Status400BadRequest, response.StatusCode);
     }
}

Can someone guide me on writing a unit test for my controller condition or is my approach above accurate?

1 Answers

The shown test above is disconnected from the controller action to be tested.

Ideally you want to create an instance of the subject under test and invoke the target member to assert the expected behavior

For example

[TestMethod]
public async Task SendCarDetails_Returns_400_When_Zero() {

    //Arrange
    MyController subject = new MyController();

    string paymentValue = "0";
    
    //Act
    IActionResult result = await subject.SendCarDetails(paymentValue);
    BadRequestObjectResult actual = result as BadRequestObjectResult ;
    
    //Assert
    Assert.IsNotNull(actual);
}
Related