gpt4 book ai didi

c# - 使用 lambda 和 Moq 对 ServiceLayer 进行单元测试

转载 作者:太空宇宙 更新时间:2023-11-03 20:30:45 25 4
gpt4 key购买 nike

我正在尝试使用 Moq 测试我的服务层在我的存储库上使用的 lambda。

服务:

public class CompanyService : TuneUpLog.ServiceLayer.ICompanyService
{
private IRepository<Company> _repository;
private IValidationDictionary _validatonDictionary;
private Guid _userId;

public CompanyService(Guid userId,IValidationDictionary validationDictionary, ObjectContext context)
: this(userId, validationDictionary, new Repository<Company>(context))
{
}

public CompanyService(Guid userId, IValidationDictionary validationDictionary, IRepository<Company> repository)
{
_validatonDictionary = validationDictionary;
_repository = repository;

if (userId == Guid.Empty)
throw new SecurityException("UserId is required");
else
_userId = userId;
}

public IEnumerable<Company> ListCompany()
{
return _repository.Find(c => c.Users.Any(u => u.UserId == _userId));
}
}

测试:

[TestMethod]
public void ListCompany_1Valid1Invalid_ReturnsValidCompany()
{
Mock<IRepository<Company>> fakeCompanyRepository = new Mock<IRepository<Company>>();

CompanyService companyService = new CompanyService(USER_ID, new ModelStateWrapper(_modelState), fakeCompanyRepository.Object);

//1 company for this user and 1 that isn't for this user
List<Company> companies = new List<Company>()
{
new Company() { Id = 1, Name = "Test Company", AccountTypeId = 1, Users = { new User() { UserId = USER_ID } } },
new Company() { Id = 2, Name = "2nd Test Company", AccountTypeId = 1, Users = { new User() { UserId = Guid.Empty } } }
};

fakeCompanyRepository.Setup(c => c.Find(It.IsAny<Expression<Func<Company, bool>>>())).Returns(companies.AsQueryable());

//count should be 1
Assert.AreEqual(1, companyService.ListCompany().Count());
}

存储库:

public interface IRepository<T> where T : class, IEntity
{
void Add(T newEntity);
void Edit(T entity);
IQueryable<T> Find(Expression<Func<T, bool>> predicate);
IQueryable<T> FindAll();
T FindById(int id);
void Remove(T entity);
void Attach(T entity);
}

测试返回的是两家公司,而不是我期望的第一家公司。我做错了什么?

最佳答案

我们使用相同的技术。您可以像这样设置模拟时捕获传入的表达式

fakeCompanyRepository.Setup(
u => u.Find(It.IsAny<Expression<Func<Company, bool>>>()))
.Returns(
//Capture the It.IsAny parameter
(Expression<Func<Company, bool>> expression) =>
//Apply it to your queryable.
companies.AsQueryable().Where(expression));

这会将您的表达式应用于公司集合。

关于c# - 使用 lambda 和 Moq 对 ServiceLayer 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7713070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com