I have unit test project and I wrote one test to check one functionality:
[Test] public async Task should_not_be_able_register_user_when_user_with_given_name_already_exists() { var mockUserRepository = new Mock<IUserRepository>(); var userService = new UserService(mockUserRepository.Object); mockUserRepository.Setup(x => x.AddAsync(user)); await userService.RegisterAsync("user", "userLastName", "fakeuser", "[email protected]", "123456789"); } In this test I want to check when user exist throw my defined exception but I have problems.
When I invoke await userService.RegisterAsync... how write assert ?
Assert.Throws(() => what should be here ?
My code: RegisterAsync looks like:
public async Task RegisterAsync(string firstName, string lastName, string username, string email, string phoneNumber) { var user = await _userRepository.GetAsync(username); if (user != null) { throw new CoreException(ErrorCode.UsernameExist, $"Username {user.Username} already exist."); } user = new User(firstName, lastName, username, email, phoneNumber); await _userRepository.AddAsync(user); } GetAsync:
public async Task<User> GetAsync(string username) => await _context.Users.SingleOrDefaultAsync(x => x.Username == username);