Andreas
Andreas

Reputation: 63

Unit test project - NUnit reference, throw exception

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.

  1. 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);

Upvotes: 1

Views: 171

Answers (1)

Nkosi
Nkosi

Reputation: 247531

Setup the mock to return a User

//...

User user = new User("firstName", "lastName", "username", "email", "phoneNumber");
mockUserRepository
    .Setup(x => x.GetAsync(It.IsAny<string>()))
    .ReturnsAsync(() => user);


//...

so that

if (user != null)
{
    throw new CoreException(ErrorCode.UsernameExist, $"Username {user.Username} already exist.");
}

will cause the subject code to throw the expected error and asserted.

This can all be summarized as

[Test]
public async Task should_not_be_able_register_user_when_user_with_given_name_already_exists() {
    //Arrange
    var mockUserRepository = new Mock<IUserRepository>();

    var userService = new UserService(mockUserRepository.Object);

    User user = new User("firstName", "lastName", "username", "email", "phoneNumber");
    mockUserRepository
        .Setup(x => x.GetAsync(It.IsAny<string>()))
        .ReturnsAsync(() => user);

    //Act
    Func<Task> act = userService.RegisterAsync("user", "userLastName", "fakeuser", "[email protected]", "123456789");

    //Assert
    CoreException exception = await Assert.ThrowsAsync<CoreException>(act);
}

Upvotes: 1

Related Questions