using AutoFixture; using Govor.Domain.Infrastructure.Extensions; using Govor.Domain.Models; using Govor.Domain.Repositories.Users; using Govor.Application.Authentication.Exceptions; using Govor.Application.Interfaces.Authentication; using Govor.Application.Services.Authentication; using Govor.Domain.Models.Users; using Govor.Domain.Repositories.Admins; using Moq; namespace Govor.Application.Tests.Services.Authentication; [TestFixture] public class AuthServiceTests { private Fixture _fixture; private Mock _passwordHasherMock; private Mock _jwtServiceMock; private Mock _usersRepositoryMock; private Mock _adminsRepositoryMock; private Mock _usernameValidatorMock; private IAccountService _accountService; [SetUp] public void SetUp() { _fixture = new Fixture(); _fixture.Behaviors .OfType() .ToList() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); _usersRepositoryMock = new Mock(); _passwordHasherMock = new Mock(); _jwtServiceMock = new Mock(); _adminsRepositoryMock = new Mock(); _usernameValidatorMock = new Mock(); _accountService = new AuthService( _usersRepositoryMock.Object, _passwordHasherMock.Object, _adminsRepositoryMock.Object, _usernameValidatorMock.Object ); } // Tests for Register action [Test] public void Given_ExistUser_When_Register_Should_Throw_UserAlreadyExistsException() { // Arrange _usersRepositoryMock.Setup(r => r.ExistsUsernameAsync(It.IsAny())).ReturnsAsync(true); // Act & Assert Assert.ThrowsAsync(async () => await _accountService.RegistrationAsync( _fixture.Create(), _fixture.Create(), _fixture.Create())); } [Test] public void Given_NotExistUser_When_Register_Should_Dont_Throw_UserNotRegisteredException() { // Arrange _usersRepositoryMock.Setup(r => r.ExistsUsernameAsync(It.IsAny())).ReturnsAsync(false); // Act & Assert Assert.DoesNotThrowAsync(async () => await _accountService.RegistrationAsync( _fixture.Create(), _fixture.Create(), _fixture.Create())); } [Test] public void Given_WrongPassword_When_Login_Should_Throw_LoginUserException() { // Arrange _usersRepositoryMock.Setup(r => r.ExistsUsernameAsync(It.IsAny())).ReturnsAsync(true); _passwordHasherMock.Setup(h => h.Verify(It.IsAny(), It.IsAny())).Returns(false); _usersRepositoryMock.Setup(u => u.FindByUsernameAsync(It.IsAny())) .ReturnsAsync(() => _fixture.Create()); // Act & Assert Assert.ThrowsAsync(async () => await _accountService.LoginAsync( _fixture.Create(), _fixture.Create())); } [Test] public void Given_NotExistUser_When_Login_Should_Throw_UserNotRegisteredException() { // Arrange _usersRepositoryMock.Setup(r => r.ExistsUsernameAsync(It.IsAny())).ReturnsAsync(false); // Act & Assert Assert.ThrowsAsync(async () => await _accountService.LoginAsync( _fixture.Create(), _fixture.Create())); } }