title: Xunit and Mock data with Moq
body: <p>I'm new to unit testing, can anyone advise how to test public method (CreateUser) below using xUnit and Moq, thanks!</p>
  
  <pre><code>public async Task&lt;bool&gt; CreateUser(UserDTO newUser)
  {
    newUser.CustomerId = _userResolverService.GetCustomerId();
    if (await CheckUserExists(newUser)) return false;
    var salt = GenerateSalt(10);
    var passwordHash = GenerateHash(newUser.Password, salt);
  
    await _usersRepository.AddAsync(new User()
    {
      Role = newUser.Role,
      CretedOn = DateTime.Now,
      CustomerId = newUser.CustomerId,
      Email = newUser.Email,
      FirstName = newUser.FirstName,
      LastName = newUser.LastName,
      PasswordHash = passwordHash,
      Salt = salt,
      UpdatedOn = DateTime.Now
    });
  
    return true;
  }
  </code></pre>
  
  <p>Private methods below
  Check if user exists simply returns number of existing users </p>
  
  <pre><code>private async Task&lt;bool&gt; CheckUserExists(UserDTO user)
      {
        var users = await _usersRepository.GetAllAsync();
        var userCount = users.Count(u =&gt; u.Email == user.Email);
        return userCount &gt; 0;
      }
  </code></pre>
  
  <p>Hash Generation</p>
  
  <pre><code>private static string GenerateHash(string input, string salt)
  {
    var bytes = System.Text.Encoding.UTF8.GetBytes(input + salt);
    var sha256 = SHA256.Create();
    var hash = sha256.ComputeHash(bytes);
  
    return ByteArrayToString(hash);
  }
  </code></pre>
  
  <p>Salt Generaion</p>
  
  <pre><code>private static string GenerateSalt(int size)
  {
    var rng = RandomNumberGenerator.Create();
    var buff = new byte[size];
    rng.GetBytes(buff);
    return Convert.ToBase64String(buff);
  }
  
  
  
  private static string ByteArrayToString(byte[] ba)
  {
    var hex = new StringBuilder(ba.Length * 2);
    foreach (byte b in ba)
      hex.AppendFormat("{0:x2}", b);
    return hex.ToString();
  }
  </code></pre>
  
  <p>Thanks,
  J</p>
  
  <p><b>EDIT 1</b></p>
  
  <p>This is what I have so far:</p>
  
  <pre><code>    [Fact]
          public async void CreateUser_True()
          {
            //arrange
            var dataSource = new Mock&lt;IRepository&lt;User, int&gt;&gt;();
            var userResolverService = new Mock&lt;IUserResolverService&gt;();
            var tokenService = new Mock&lt;ITokenService&gt;();
  
        var users = new List&lt;User&gt;();
        users.Add(new User()
        {
          Email = "test@test.com",
          CustomerId = 1
        });
        dataSource.Setup(m =&gt; m.GetAllAsync()).ReturnsAsync(users); // Error Here with converting async task to IEnumerable...
  
            var accountService = new AccountService(dataSource.Object,userResolverService.Object,tokenService.Object);
  
  
            //act
  
  
            //assert
  
  
          }
  </code></pre>
  
  <p>Main problem is that I have no idea how to Mock, set up behavior of private Method "CheckUserExists", as it's calling IRepository which is mocked for class, so will this in this case return my mock setup for GetAllAsync from this private method?</p>
  
  <p>EDIT 2</p>
  
  <pre><code>public async Task&lt;TEntity&gt; AddAsync(TEntity entity)
  {
    if (entity == null)
    {
      throw new ArgumentNullException(nameof(entity));
    }
    _entities.Add(entity);
    await _context.SaveChangesAsync();
    return entity;
  }
  </code></pre>
  
  <p><b>EDIT 3</b></p>
  
  <pre><code>[Fact]
  public async void CreateUser_True()
  {
    //arrange
    var users = new List&lt;User&gt;();
    users.Add(new User()
    {
      Email = "test@test.com",
      CustomerId = 1
    });
    _dataSource.Setup(m =&gt; m.GetAllAsync()).ReturnsAsync(users);
    _dataSource.Setup(m =&gt; m.AddAsync(It.IsAny&lt;User&gt;())).Returns&lt;User&gt;(Task.FromResult);
    var accountService = new AccountService(_dataSource.Object, _userResolverService.Object, _tokenService.Object);
  
  
    //act
    var result = await accountService.CreateUser(new UserDTO()
    {
      Email = "truetest@test.com"
    });
  
    var updatedUsersList = await _dataSource.Object.GetAllAsync();
    var usersCount = updatedUsersList.Count();
  
    //assert
    Assert.True(result);
    Assert.Equal(2, usersCount);
  
  }
  </code></pre>