[英]How to write testcases using Xunit test for extension method like Any
实际上这是我的服务层。 我想通过 Xunit 测试来测试创建帐户的方法。 我该如何继续?
public class UserService :IUserService // service
{
#region Property
private readonly IAppDbContext _appDbContext;
#endregion
#region Constructor
public UserService(IAppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
#endregion
public int Create(User model)
{
_appDbContext.Users.Add(model);
_appDbContext.SaveChanges();
return model.Id;
}
public bool CheckAccount(User data)
{
if (this._appDbContext.Users.Any(x => x.UserName == data.UserName))
{
return false;
}
else
{
return true;
}
}
public string CheckDetails(User data)
{
if (this._appDbContext.Users.Any(x => x.Password == data.Password) &&
this._appDbContext.Users.Any(x => x.UserName == data.UserName))
{
var userid = "";
var obj = this._appDbContext.Users.Where(x => x.UserName == data.UserName);
foreach (var i in obj)
{
userid = i.Id.ToString();
}
return userid;
}
else
{
return null;
}
}
}
}
请告诉我如何通过 xunit 测试在用户服务中测试此方法
很简单。 您需要使用[Theory]和[InlineData] XUnit属性。 我为你准备了一个小例子
public class UnitTest
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
[Theory]
[InlineData("First")]
public void Test1(string productName)
{
var productList = new List<Product>
{
new()
{
Id = 1,
Name = "First"
},
new()
{
Id = 2,
Name = "Second"
}
};
Assert.True(productList.Any(product => product.Name == productName));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.