How to call service class in mock Framework with x-unit method ASP Web API .Net 6?

17 views Asked by At

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.

1

There are 1 answers

0
Mark Seemann On

It sounds as though UserService is a base class that takes some dbcontext as a constructor argument. If so, try passing it as a constructor parameter:

var userrepo = new Mock<UserService>(dbcontext);

You may also want to experiment with setting CallBase = true on userrepo. I can't say whether or not it's going to address the issue, as I don't have enough information from the OP.