Search code examples
asp.net-corexunit

Catch StatusCode from execution value in Xunit


I want to compare the return value from controller execution whether that fulfill the condition or not. From debugging I noticed the 'StatusCode' but not got an way to catch that value for comparing. My Code for testing is

    public void PostAmount_Withdraw_Returns_Null()
    {
        // Arrange
        Amount amount = new Amount() { Id = 0, PaymentDate = DateTime.Today, 
             PaymentTypeId = 3, PaymentAmount = 500, ClientId = 1, Balance = 0 };

        _accountServiceMock.Setup(s => s.Withdraw(amount)).Throws(new Exception());
        
        var target = SetupAmountsController();

        //Act
        var actual = target.PostAmount(amount);

        //Assert

        actual.ShouldNotBeNull();
        //actual.Value.ShouldBe(response);
    }

What call controller methods below : -

    public ActionResult<Amount> PostAmount(Amount amount)
    {
        try
        {
            if (amount.PaymentTypeId == 1)
            {
                _accountService.Deposit(amount);
            }
            else if (amount.PaymentTypeId == 2)
            {
                _accountService.Withdraw(amount);
            }
            else
            {
                return Problem("Model 'Amounts'  is null.");
            }
            return new OkObjectResult(new { Message = "Payment Success!" });
        }
        catch (DbUpdateConcurrencyException)
        {
            return Problem("There was error for updating model Payment");
        }
    }

And, returned the value after execution from Unit Test enter image description here

I want to give condition likes below: -

 actual.Result.StatusCode = HttpStatusCode.BadRequest or 
 actual.Result.StatusCode = 500

Solution

  • Just got the answer. It will be likes below: -

     (actual.Result as ObjectResult).StatusCode.ShouldBe((int)HttpStatusCode.InternalServerError);
    

    you need to define here 'status code' what want to compare. In my case it was 500.