Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I use UnitOfWork with repository in WebAPI dotnet 6 and want to use XUnit for test
I use below code but when run the test the result is:

System.NullReferenceException : Object reference not set to an instance of an object.

What I have tried:

C#
public interface IUnitOfWork : IDisposable
{
    IUserRepository UserRepository { get; }
}

public class UnitOfWork : IUnitOfWork
{
    protected readonly DatabaseContext db;

    private IUserRepository userRepository;
    public IUserRepository UserRepository
    {
        get
        {
            if (userRepository == null)
            {
                userRepository = new UserRepository(db);
            }

            return userRepository;
        }
    }

    //...
}
C#
public interface IUserRepository : IGenericRepository<UserRole>
{
    Task<User> GetUserWithRolesAsync(string username);
}

public class UserRepository : GenericRepository<User>, IUserRepository
{
    public async Task<User> GetUserWithRolesAsync(string username)
    {
        //...
    }
}
C#
private readonly IUnitOfWork _uow;
public AuthController(IUnitOfWork uow) : base(uow)
{
    _uow = uow;
}

[HttpPost("authenticate")]
public async Task<IActionResult> Authenticate([FromBody] UserLoginViewModel Request)
{
    User user = await _uow.UserRepository.GetUserWithRolesAsync(Request.Username);
    //....
}
C#
[Fact]
public async Task Authenticate_WithInvalidUsernamePassword_ReturnsNotFound()
{
    // Arrange
    var unitOfWorkStub = new Mock<IUnitOfWork>();
    unitOfWorkStub.Setup(uow => uow.UserRepository.GetUserWithRolesAsync(It.IsAny<string>())).ReturnsAsync((User)null);

    var jwtAuthenticatorManagerStub = new Mock<IJwtAuthenticatorManager>();
    var localizorStub = new Mock<IStringLocalizer<SharedTranslate>>();

    var controller = new AuthController(unitOfWorkStub.Object, localizorStub.Object, jwtAuthenticatorManagerStub.Object);
    UserLoginViewModel userLoginViewModel = new UserLoginViewModel
    {
        Username = "admin",
        Password = "admin@123"
    };

    // Act
    var result = await controller.Authenticate(userLoginViewModel);

    // Assert
    Assert.IsType<NotFoundResult>(result);
}
Posted
Updated 5-Jan-22 22:39pm
v2

1 solution

That error means you're trying to access a method or property on an object which has not been initialized.

At a guess, it's probably the protected readonly DatabaseContext db; field in your UnitOfWork class, which is not initialized by any of the code you have shown.

But that's just a guess, because you haven't told us where the error occurs, and we cannot run your code.

You need to debug your code. Step through it line by line until you identify the object which is null when it shouldn't be. Then work out why it hasn't been initialized.

We can't do that for you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900