如何在 xunit 中编写返回任务的测试

问题描述 投票:0回答:2

这个类需要测试,但我不知道测试返回任务的类

public async Task CreateUser(User request)
        {
            try
            {
                var _user = new User()
                {
                    FullName = request.FullName,
                    DOB = request.DOB,
                    Gender = request.Gender,
                    AddressDetail = request.AddressDetail,
                    CityId = request.CityId,
                    DistrictId = request.DistrictId,
                    WardsId = request.WardsId,
                    Phone = request.Phone,
                    Password = EncryptPassword(request.Password).GetAwaiter().GetResult().ToString(),
                    RoleId = 2,
                    Status = 1,
                };

                await _userRespository.Create(_user).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

如何编写返回任务的测试?我真的需要你的帮助。

这是我的测试功能如下:

 [Fact]
        public async Task CreateUser_Task_Complete()
        {   
            //Arrange
            var mock = new Mock<IGenericService<User>>();
            var mockConfig = new Mock<IConfiguration>();

             User user = new User() { Id = 1, FullName = "abc", AddressDetail = "A", CityId = "123", DistrictId = "123", WardsId = "123", Password = "123456", Gender = "male", Phone = "0123456789", DOB = "5/5/1990", Avatar = "" }
        ;


            mock.Setup(_ => _.Create(user)).Returns(Task.FromResult(user));
            
            //Act
            var service = new UserService(mock.Object, mockConfig.Object);

            var response = service.CreateUser(user);


            //Assert
            await service.CreateUser(user);


        }
.net unit-testing testing mocking xunit
2个回答
2
投票

您可以检查任务是否成功完成。您可以重构为这样的东西,而不是使用

await


Task createUserTask = service.CreateUser(user);
createUserTask.Wait();
Assert.True(createUserTask.IsCompletedSuccessfully);

0
投票

与@John Nyingi的答案相同,但只是使用异步测试方法

public async Task Test()
{
    Task createUserTask = service.CreateUser(user);
    await createUserTask; // there is no lock of the current thread here

    Assert.True(createUserTask.IsCompletedSuccessfully);
}
© www.soinside.com 2019 - 2024. All rights reserved.