A mocking abstract class that has constructor dependencies (with Moq)

I have an abstract class whose constructor needs a 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 element from the collection passed to the constructor must implement:

 public interface IDate { DateTime Date { get; } } 

If I write my own layout, it will look like this:

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

Can I achieve this with Moq?

+6
source share
1 answer

You can do something line by line:

 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 is 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); } 
+11
source

Source: https://habr.com/ru/post/927094/


All Articles