2012-01-06 93 views
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 & validatorDI 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); 
    } 
} 
+1

確定有關此類型的約束?它應該只是T:Entity – 2012-01-06 09:23:54

+1

可能的重複[使用IoC進行單元測試](http://stackoverflow.com/questions/1465849/using-ioc-for-unit-testing) – 2012-01-06 09:46:40

+0

@MylesMcDonnell爲什麼不呢? – lexeme 2012-01-06 09:54:28

回答

1

是的,絕對。讓你的單元測試用mock實例化服務,讓你的應用程序通過你的真實實現。

例如(使用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();