如何测试这种异步删除方法?

时间:2019-05-16 03:55:41

标签: c# nunit tdd moq

我正在尝试测试存储库Delete方法的设置没有成功:

    [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));
    }

此方法测试通过,但是如果我将.Wait()放在service.DeleteUser(USER_ID)之后,则测试不通过,因为它引发了意外的NullException。

服务和存储库方法均为async,并且仅返回空的Task对象。

1 个答案:

答案 0 :(得分:1)

看起来 DeleteAsync -mock应该类似于 AddAsync -mock并返回 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;
      });  

测试可以是异步

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

      await service.DeleteUser(USER_ID);

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