依赖关系注入和测试加倍

本文关键字:测试 关系 注入 依赖 | 更新日期: 2023-09-27 18:19:32

我是使用dependency injection的新手。例如,我有这样一个示例服务:

public class ValidationService<T> where T : Entity<T>
{
    private IRepository<T> repository;
    private IValidator<T>  validator;
    public ValidationService(IRepository<T> repository, IValidator<T> validator)
    {
        this.repository = repository;
        this.validator  = validator;
    }
    public String ValidationMessage 
    { 
        get;
        private set;
    }
    public Boolean TryValidate(Guid Id)
    {
        try 
        {
            var item = repository.Get(Id);
            if(null != item)
            {
                this.Validator.ValidateAndThrow(entity);
                return true;
            }
            this.ValidationMessage = String.Format("item {0} doesn't exist in the repository", Id);
        }
        catch(ValidationException ex)
        {
            this.ValidationMessage = ex.Message;
        }
        return false;
    }
}

我可以对repositoryvalidator使用测试替身(mocks or fakes(并在UI项目(ASP.NET MVC(内对DI使用相同的服务吗?

谢谢!

编辑

代码已成功运行,并且在输出中我true.

public class Entity<T> where T : Entity<T>
{
    public Boolean GotInstantiated { get { return true; } }         
}
public class Service<T> where T : Entity<T>
{
    public Boolean GetInstantiated(T entity)
    {
        return entity.GotInstantiated;
    }
}
public class Dunce : Entity<Dunce>
{       
}
class Program
{
    public static void Main(String[] args)
    {
        var instance = new Dunce();
        var service  = new Service<Dunce>();
        Console.Write(service.GetInstantiated(instance) + Environment.NewLine);
        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}

依赖关系注入和测试加倍

是的,绝对是。 让你的单元测试用模拟实例化服务,让你的应用程序通过你的实际实现。

示例(使用最小起订量(:

public class Entity<T> where T : Entity<T>{}
public class MyEntity : Entity<MyEntity>{}

var mockValidator = new Mock<IValidator<MyEntity>>();
var mockRepository = new Mock<IRepository<MyEntity>>();
var id = Guid.NewGuid();
var entity = new MyEntity();
mockRepository.Setup(r => r.Get(id)).Returns(entity);
mockValidator.Setup(v => v.ValidateAndThrow(entity));
Assert.IsTrue(new ValidationService<MyEntity>(mockRepository.Object, mockValidator.Object).TryValidate(id));
mockRepository.VerifyAll();
mockValidator.VerifyAll();