2012-10-06 7 views
6

Ich habe eine abstrakte Klasse, deren Konstruktor Sammlung Argument benötigt. Wie kann ich meine Klasse verspotten, um sie zu testen?Mocking abstrakte Klasse, die Konstruktor Abhängigkeiten hat (mit Moq)

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

     public DateTime From { get { ... } } 

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

Jedes Element aus der Sammlung zu Konstruktor übergeben muß implementieren:

public interface IDate 
{ 
    DateTime Date { get; } 
} 

Wenn ich meine Gewohnheit verspotten schreiben würde es so aussehen:

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

Kann ich dies erreichen mit Moq ?

Antwort

11

Sie können entlang der Linien von etwas tun:

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 .. 

Hier ist ein sehr einfaches Beispiel:

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

wirkt wie ein Zauber :) – Kuba

+0

Froh, dass ich helfen könnte :) –

Verwandte Themen