We will be performing unit testing in ASP.NET Web API using .NET 6. We are attempting unit testing using the Moq framework with the xUnit testing method. To begin, we download the Moq package. Next, we create a Service Class object using Moq methods. With this object, we set up the controller function using the Returns method. Then, we utilize the controller object, incorporating the previously created Moq object, to obtain our desired result.
Problem: There is dbcontext added as dependency injection in UserService. when calling method from that service which is "GetUsers " dbcontext is null.
Controller : User ServiceClass : UserService Interface : IUserService
var result = new BaseResponseModel()
{
StatusCode = (int)ResponseType.Success,
Data = new UserModel
{
Id = 10002
},
Message = null
};
var userrepo = new Mock<UserService>();
userrepo.Setup(x => x.GetUsers(It.IsAny<long>())).ReturnsAsync(result);
var controller = new UserController(userrepo.Object);
BaseResponseModel response = await controller.GetEmployerUserList(10002);
dB context should be initialized and I should able to database.
UserServiceandUserController? At least the relevant parts from your question perspective.