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 02 Answers
Reset to default 0Your 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
版权声明:本文标题:c# - Initializing internal variables with Moq in a unit test - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745561613a2663504.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论