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.
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.