-1

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
  • Could you please share with us the class definitions of the UserService and UserController? At least the relevant parts from your question perspective. Commented Feb 23, 2024 at 13:14

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.