如何编写在 xunit 中返回任务的测试
这个类需要测试,但我不知道测试返回任务的类
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);
}
This class needs to be Tested, but I do not have any idea to test a class that returns a Task
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;
}
}
How can I write a test that returns a Task? I really need your bits of help.
This is my Test function is below:
[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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以检查任务是否成功完成。
You can check whether the Task was completed Successfully.
与 @John Nyingi 的答案相同,但只是使用异步测试方法
The same, as @John Nyingi's answer, but just with async test method