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);
}
CodePudding user response:
You can check whether the Task was completed Successfully. Instead of using await
, you can refactor to something like this;
Task createUserTask = service.CreateUser(user);
createUserTask.Wait();
Assert.True(createUserTask.IsCompletedSuccessfully);