依赖注入和测试加倍

时间:2012-01-06 08:38:05

标签: c# unit-testing dependency-injection

我刚开始使用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;
    }
}

我可以为mocks or fakes使用测试双打(repository)吗? validator并在UI项目(DI)内使用与ASP.NET MVC相同的服务?

谢谢!

修改

代码已成功运行,在输出中我有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);
    }
}

1 个答案:

答案 0 :(得分:1)

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

示例(使用MOQ):

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();