I am using NUnit, and C# .NET 6. I am Mocking the service to return some data. However the service is always returning null in the Controller while executing the test case.
Service Method:
public async Task<Result<TResponseModel>> InvokeGenericService<TRequestModel, TResponseModel,
TRequestEntity, TResponseEntity>(ControllerContext controllerContext, TRequestModel
requestModel, AccountIndexModel cache, string pApiNameInConfig, CacheFilterParams
cacheFilterParams = null)
where TResponseModel : class, new()
where TRequestEntity : class, new()
where TResponseEntity : class, new()
{
//code....
}
Controller:
public async Task<IActionResult> UpdatePayment(AccountIndexModel cache, string
accountIndex, [FromBody] UpdatePaymentRequestModel model)
{
var response = await
genericService.InvokeGenericService<UpdatePaymentRequestModel,
UpdatePaymentResponseModel, UpdatePaymentRequestEntity,
UpdatePaymentResponseEntity>(ControllerContext, model, cache,
"UpdateReceiptsPayment", new CacheFilterParams { AccountIndex = accountIndex
});
if (response.HasErrors) // response is always Null, despite mocking
{
// Other code
}
}
Test:
[Test]
public void InvokeUpdatePayment_WithValidRequest_ReturnsSuccessResponse()
{
this._mockIgenericService.Setup(service =>
service.InvokeGenericService<UpdatePaymentRequestModel, UpdatePaymentResponseModel,
UpdatePaymentRequestEntity, UpdatePaymentResponseEntity>
(this.controllerContext.Object, It.IsAny<UpdatePaymentRequestModel>(),
It.IsAny<AccountIndexModel>(), "UpdateReceiptsPayment", It.IsAny<CacheFilterParams>
()))
.Returns(Task.FromResult(new Models.Result<UpdatePaymentResponseModel>
{
ResultData = GenerateStub.GetValidUpdatePaymentResponse(),
ErrorList = null,
}));
var model = GenerateStub.GetValidUpdatePaymentRequestModel();
var okResult = this._receiptsPaymentsController.UpdatePayment(
GenerateStub.GetValidAccountIndexModel(), "2", model).GetAwaiter().GetResult() as
OkObjectResult; // It invokes Controller action method
Assert.IsNotNull(okResult);
}