admin管理员组

文章数量:1431435

I am trying to create a unit test for a controller that returns a status code based on a call from a service. Since the test doesn't actually call the service the control flow throws a null reference exception when the test is running. I am hoping someone can assist with insights on how to resolve this. Thanks Controller:

     [HttpPost]
 public async Task<IActionResult> CreateTransaction([FromBody] TransactionReqDto payload)
 {
 
     if (payload == null) return BadRequest();
     var res = await _service.CreateTransactionAsync(payload);

     switch (res.Status)
     {
         case true:
             return Ok(res);
         case false:
             return UnprocessableEntity(res);
     }
 }

Unit Test:

   public async Task CreateTransaction_OnSuccess_ReturnStatusCode200()
{
//Arrange
var mockTransactionService = new Mock<ITransactionService>();
var transactionRequest = TransactionFixture.CreateTransaction();
var transactionResponse = new TransactionResDto { Status = true };
mockTransactionService.Setup(service => service.CreateTransactionAsync(transactionRequest))
                      .ReturnsAsync(transactionResponse);
var mockTransactionController = new TransactionController(mockTransactionService.Object);
//Act
var result = (OkObjectResult) await mockTransactionController.CreateTransaction(TransactionFixture.CreateTransaction());
//Assert
result.Should().BeOfType<OkObjectResult>();
}

Error while running test:

Message:  System.NullReferenceException : Object reference not set to an instance of an object.

Stack Trace:  TransactionController.CreateTransaction(TransactionReqDto payload) line 35 TransactionControllerUnitTest.CreateTransaction_OnSuccess_ReturnStatusCode200() line 57 --- End of stack trace from previous location ---

I debugged the code and realized that the variable "res" is returning null since createTransactionAsync metho wasn't called. Any assistance with this would be appreciated.

I am trying to create a unit test for a controller that returns a status code based on a call from a service. Since the test doesn't actually call the service the control flow throws a null reference exception when the test is running. I am hoping someone can assist with insights on how to resolve this. Thanks Controller:

     [HttpPost]
 public async Task<IActionResult> CreateTransaction([FromBody] TransactionReqDto payload)
 {
 
     if (payload == null) return BadRequest();
     var res = await _service.CreateTransactionAsync(payload);

     switch (res.Status)
     {
         case true:
             return Ok(res);
         case false:
             return UnprocessableEntity(res);
     }
 }

Unit Test:

   public async Task CreateTransaction_OnSuccess_ReturnStatusCode200()
{
//Arrange
var mockTransactionService = new Mock<ITransactionService>();
var transactionRequest = TransactionFixture.CreateTransaction();
var transactionResponse = new TransactionResDto { Status = true };
mockTransactionService.Setup(service => service.CreateTransactionAsync(transactionRequest))
                      .ReturnsAsync(transactionResponse);
var mockTransactionController = new TransactionController(mockTransactionService.Object);
//Act
var result = (OkObjectResult) await mockTransactionController.CreateTransaction(TransactionFixture.CreateTransaction());
//Assert
result.Should().BeOfType<OkObjectResult>();
}

Error while running test:

Message:  System.NullReferenceException : Object reference not set to an instance of an object.

Stack Trace:  TransactionController.CreateTransaction(TransactionReqDto payload) line 35 TransactionControllerUnitTest.CreateTransaction_OnSuccess_ReturnStatusCode200() line 57 --- End of stack trace from previous location ---

I debugged the code and realized that the variable "res" is returning null since createTransactionAsync metho wasn't called. Any assistance with this would be appreciated.

Share Improve this question asked Nov 19, 2024 at 12:41 Seyi AgboolaSeyi Agboola 544 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 0

Your setup only works for the one instance of the method parameter used (variable transactionRequest). But later you create another instance when calling the method. You can also use It.IsAny to ignore the parameter entirely and make the setup work for any value.

@Jonas thanks for the suggestion. This is my updated code and test ran successfully.

public async Task CreateTransaction_OnSuccess_ReturnStatusCode200()
{
    //Arrange
    var mockTransactionService = new Mock<ITransactionService>();
    var transactionRequest = TransactionFixture.CreateTransaction();
    var transactionResponse = new TransactionResDto { Status = true };
    mockTransactionService.Setup(service => service.CreateTransactionAsync(It.IsAny<TransactionReqDto>()))
                        .ReturnsAsync(transactionResponse);
    var mockTransactionController = new TransactionController(mockTransactionService.Object);
    //Act
    var result = (OkObjectResult) await mockTransactionController.CreateTransaction(TransactionFixture.CreateTransaction());
    //Assert
    result.Should().BeOfType<OkObjectResult>();
}

本文标签: cInitializing internal variables with Moq in a unit testStack Overflow