'How to write testcases using Xunit test for extension method like Any
Actually this is my service layer. I want to test a create account method by Xunit testing. How can I proceed further?
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;
}
}
}
}
Please tell ,how to I test this method are there in User service by xunit testing
Solution 1:[1]
That's simple. You need to use [Theory] and [InlineData] XUnit attributes. I prepared a small example for you
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));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dmitry Grebennikov |
