0

I´m trying without success to test a setup a repository Delete method:

    [SetUp]
    public void Setup()
    {
        var admin = new User
        {
            Id = ADMIN_USER_ID,
            Name = "admin",
            Lastname = "admin",
            Username = "admin"
        };

        var normalUser = new User
        {
            Id = USER_ID,
            Name = "user",
            Lastname = "user",
            Username = "user"
        };

        _userList.Add(admin);
        _userList.Add(normalUser);

        _userRepository.Setup(u => u.DeleteAsync(It.IsAny<string>())).Callback((string id) =>
        {
            var user = _userList.Find(p => p.Id == id);
            if (user != null)
                _userList.Remove(user);
        });

        _userRepository.Setup(u => u.AddAsync(It.IsAny<User>())).Returns((User u) =>
        {
            u.Id = Guid.NewGuid().ToString();
            _userList.Add(u);
            return Task.CompletedTask;
        });
    }

    [Test]
    public void Should_Delete_Normal_User()
    {
        var service = GetService();

        service.DeleteUser(USER_ID); // Here should run Synchronously using .Wait()

        Assert.ThrowsAsync<UserNotFoundException>(() => service.GetUser(USER_ID));
    }

This method Test pass, but if I put the .Wait() after the service.DeleteUser(USER_ID) the test doesn´t pass because it throws an unexpected NullException.

Both the service and repository methods are async and returns only a empty Taskobject.

gog
  • 11,788
  • 23
  • 67
  • 129
  • The mocked DeleteAsync did not return anything. So the result is null and that should be the reason for the NRE – Sir Rufo May 16 '19 at 04:23
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Sir Rufo May 16 '19 at 04:24
  • BTW NUnit supports async test methods to test async methods. There is no need to use wait – Sir Rufo May 16 '19 at 04:27

1 Answers1

2

It looks like the DeleteAsync-mock should be like AddAsync-mock and return Task:

  _userRepository
    .Setup(u => u.DeleteAsync(It.IsAny<string>()))
    .Returns((string id) =>
      {
          var user = _userList.Find(p => p.Id == id);
          if (user != null)
              _userList.Remove(user);

          return Task.CompletedTask;
      });  

The test can be async:

  [Test]
  public async Task Should_Delete_Normal_User()
  {
      var service = GetService();

      await service.DeleteUser(USER_ID);

      Assert.ThrowsAsync<UserNotFoundException>(() => service.GetUser(USER_ID));
  }
vladimir
  • 13,428
  • 2
  • 44
  • 70