如何在 xunit 中编写具有 return 任务的测试
How to write a test that has return a Task in xunit
这个 class 需要测试,但我不知道要测试一个 class 那个 returns 一个任务
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;
}
}
如何编写 returns 任务的测试?我真的需要你的一点帮助。
下面是我的测试函数:
[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);
}
您可以检查任务是否成功完成。您可以重构为这样的东西,而不是使用 await
;
Task createUserTask = service.CreateUser(user);
createUserTask.Wait();
Assert.True(createUserTask.IsCompletedSuccessfully);
这个 class 需要测试,但我不知道要测试一个 class 那个 returns 一个任务
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;
}
}
如何编写 returns 任务的测试?我真的需要你的一点帮助。
下面是我的测试函数:
[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);
}
您可以检查任务是否成功完成。您可以重构为这样的东西,而不是使用 await
;
Task createUserTask = service.CreateUser(user);
createUserTask.Wait();
Assert.True(createUserTask.IsCompletedSuccessfully);