0
我是新使用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
與DI
UI項目中(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);
}
}
確定有關此類型的約束?它應該只是T:Entity – 2012-01-06 09:23:54
可能的重複[使用IoC進行單元測試](http://stackoverflow.com/questions/1465849/using-ioc-for-unit-testing) – 2012-01-06 09:46:40
@MylesMcDonnell爲什麼不呢? – lexeme 2012-01-06 09:54:28