2012-10-06 38 views
6

Tengo una clase abstracta cuyo constructor necesita un argumento de colección. ¿Cómo puedo burlarme de mi clase para probarlo?Mocking clase abstracta que tiene dependencias de constructor (con Moq)

public abstract class QuoteCollection<T> : IEnumerable<T> 
     where T : IDate 
    { 
     public QuoteCollection(IEnumerable<T> quotes) 
     { 
      //... 
     } 

     public DateTime From { get { ... } } 

     public DateTime To { get { ... } } 
    } 

Cada elemento de la colección pasó a constructor debe aplicar:

public interface IDate 
{ 
    DateTime Date { get; } 
} 

Si me gustaría escribir mi costumbre burlarse de que se vería así:

public class QuoteCollectionMock : QuoteCollection<SomeIDateType> 
{ 
    public QuoteCollectionMock(IEnumerable<SomeIDateType> quotes) : base(quotes) { } 
} 

¿Puedo lograr esto con Moq ?

Respuesta

11

Usted puede hacer algo en la línea de:

var myQuotes = GetYourQuotesIEnumerableFromSomewhere(); 
// the mock constructor gets the arguments for your classes' ctor 
var quoteCollectionMock = new Mock<QuoteCollection<YourIDate>>(MockBehavior.Loose, myQuotes); 

// .. setup quoteCollectionMock and assert as you please .. 

Aquí hay un ejemplo muy sencillo:

public abstract class AbstractClass 
{ 
    protected AbstractClass(int i) 
    { 
     this.Prop = i; 
    } 
    public int Prop { get; set; } 
} 
// ... 
    [Fact] 
    public void Test() 
    { 
     var ac = new Mock<AbstractClass>(MockBehavior.Loose, 10); 
     Assert.Equal(ac.Object.Prop, 10); 
    } 
+0

funciona como un encanto :) – Kuba

+0

contenta de haber podido ayudar :) –

Cuestiones relacionadas