Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking abstract class that has constructor dependencies (with Moq)

I have an abstract class whose constructor needs collection argument. How can I mock my class to test it ?

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

        public DateTime From { get { ... } }

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

Each item from collection passed to constructor must implement:

public interface IDate
{
    DateTime Date { get; }
}

If I would write my custom mock it would look like this:

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

Can I achieve this with Moq ?

like image 834
Kuba Avatar asked Oct 06 '12 12:10

Kuba


1 Answers

You can do something along the lines of:

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

Here's a very simple example:

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);
    }
like image 111
Vlad Ciobanu Avatar answered Sep 27 '22 16:09

Vlad Ciobanu