2 years ago

#26242

test-img

SajjadZare

Use XUnit with UnitOfWork and Repository in .NET 6

I use UnitOfWork with repository in an ASP.NET Core 6 Web API and want to use XUnit for testing. I use the code shown below, and it works.

I have two questions:

  1. I use accept-language in the methods to know what is the language for returning correct error messages. How can I add accept-language for test?

  2. How should I use token that I get with Authenticate method?

UnitOfWork

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;
        }
    }

    //...
}

UserRepository

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

public class UserRepository : GenericRepository<User>, IUserRepository
{
    public async Task<User> GetUserWithRolesAsync(string username)
    {
        //...
    }
}

AuthController

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);
    //....
}

Test method:

[Fact]
public async Task Authenticate_WithInvalidUsernamePassword_ReturnsNotFound()
{
    // Arrange
    var dbOption = new DbContextOptionsBuilder<DatabaseContext>().UseSqlServer("connection string").Options;
    DatabaseContext databaseContext = new DatabaseContext(dbOption);
    databaseContext.Database.EnsureCreated();

    var jwtAuthenticatorManager = new JwtAuthenticatorManager("key");

    var unitOfWorkStub = new Mock<IUnitOfWork>();

    UserRepository userRep = new UserRepository(databaseContext);
    unitOfWorkStub.SetupGet(uow => uow.UserRepository).Returns(userRep);

    var options = Options.Create(new LocalizationOptions { ResourcesPath = "Resources" });
    var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);
    var localizer = new StringLocalizer<SharedTranslate>(factory);

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

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

    // Assert
    result.Should().BeOfType<NotFoundResult>();
}

c#

xunit

xunit.net

.net-6.0

0 Answers

Your Answer

Accepted video resources