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