我有一个抽象类,其构造函数需要集合参数。我怎么模仿我的班级来测试呢?
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实现这个目标吗?
答案 0 :(得分:14)
您可以采取以下措施:
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);
}