我正在尝试找出分解单元测试的正确方法。
给定以下两个类,一个是 a CategoryService
,另一个是CategoryValidator
using FluentValidation
,您将如何编写这些测试?
我尝试为服务编写一个测试,为验证器编写一个测试,但是如何测试验证在服务中是否有效?或者这是否超出了服务测试的范围,应该包含在验证器测试中?
在该AddCategory
方法中,我正在测试验证器中不存在类别名称。我如何在单元测试中测试它?或者那是一个集成测试?
分类服务
public class CategoryService : ValidatingServiceBase, ICategoryService
{
private readonly IUnitOfWork unitOfWork;
private readonly IRepository<Category> categoryRepository;
private readonly IRepository<SubCategory> subCategoryRepository;
private readonly IValidationService validationService;
public CategoryService(
IUnitOfWork unitOfWork,
IRepository<Category> categoryRepository,
IRepository<SubCategory> subCategoryRepository,
IValidationService validationService)
: base(validationService)
{
this.unitOfWork = unitOfWork;
this.categoryRepository = categoryRepository;
this.subCategoryRepository = subCategoryRepository;
this.validationService = validationService;
}
public bool AddCategory(Category category)
{
var validationResult = validationService.Validate(category);
if (!validationResult.IsValid)
return false;
categoryRepository.Add(category);
return true;
}
}
类别验证器
public class CategoryValidator : AbstractValidator<Category>
{
public CategoryValidator(ICategoryService service)
{
RuleFor(x => x.Name)
.NotEmpty()
.Must((category, name) =>
{
return service.GetCategories().SingleOrDefault(x => x.Name == name) == null;
});
}
}