10

我有一个抽象类,其构造函数需要集合参数。我怎样才能模拟我的班级来测试它?

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

        public DateTime From { get { ... } }

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

传递给构造函数的集合中的每个项目都必须实现:

public interface IDate
{
    DateTime Date { get; }
}

如果我要编写自定义模拟,它将如下所示:

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

我可以通过 Moq 实现这一目标吗?

4

1 回答 1

20

您可以执行以下操作:

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

这是一个非常简单的例子:

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);
    }
于 2012-10-06T13:30:35.747 回答