这是我的目标:Autofixture生成自定义列表
public class Symbol
{
private readonly string _identifier;
private readonly IList<Quote> _historicalQuotes;
public Symbol(string identifier, IEnumerable<Quote> historicalQuotes = null)
{
_identifier = identifier;
_historicalQuotes = historicalQuotes;
}
}
public class Quote
{
private readonly DateTime _tradingDate;
private readonly decimal _open;
private readonly decimal _high;
private readonly decimal _low;
private readonly decimal _close;
private readonly decimal _closeAdjusted;
private readonly long _volume;
public Quote(
DateTime tradingDate,
decimal open,
decimal high,
decimal low,
decimal close,
decimal closeAdjusted,
long volume)
{
_tradingDate = tradingDate;
_open = open;
_high = high;
_low = low;
_close = close;
_closeAdjusted = closeAdjusted;
_volume = volume;
}
}
我需要填充的报价列表符号的一个实例。
在我的测试中,我想验证我可以返回收盘价低于或高于特定值的所有报价。这是我的测试:
[Fact]
public void PriceUnder50()
{
var msftIdentifier = "MSFT";
var quotes = new List<Quote>
{
new Quote(DateTime.Parse("01-01-2009"), 0, 0, 0, 49, 0, 0),
new Quote(DateTime.Parse("01-02-2009"), 0, 0, 0, 51, 0, 0),
new Quote(DateTime.Parse("01-03-2009"), 0, 0, 0, 50, 0, 0),
new Quote(DateTime.Parse("01-04-2009"), 0, 0, 0, 10, 0, 0)
};
_symbol = new Symbol(msftIdentifier, quotes);
var indicator = new UnderPriceIndicator(50);
var actual = indicator.Apply(_symbol);
Assert.Equal(2, actual.Count);
Assert.True(actual.Any(a => a.Date == DateTime.Parse("01-01-2009")));
Assert.True(actual.Any(a => a.Date == DateTime.Parse("01-04-2009")));
Assert.True(actual.Any(a => a.Price == 49));
Assert.True(actual.Any(a => a.Price == 10));
}
好的。
现在,我想要使用Autofixture,我是一个真正的初学者。我已经在网上阅读了关于这个工具的几乎所有东西(作者的博客,codeplex FAQ,github源代码)。我了解自动混合的基本特征,但现在我想在我的真实项目中使用自动混合。这是我到目前为止所尝试的。
var msftIdentifier = "MSFT";
var quotes = new List<Quote>();
var random = new Random();
fixture.AddManyTo(
quotes,
() => fixture.Build<Quote>().With(a => a.Close, random.Next(1,49)).Create());
quotes.Add(fixture.Build<Quote>().With(a => a.Close, 49).Create());
_symbol = new Symbol(msftIdentifier, quotes);
// I would just assert than 49 is in the list
Assert.True(_symbol.HistoricalQuotes.Contains(new Quote... blabla 49));
理想情况下,我宁愿直接创建符号的灯具,但我不知道如何自定义我的列表引号。我不确定我的测试是否是通用的,因为在另一个测试中,我需要检查一个特定的值是否在上面,所以我要复制“夹具代码”并手动添加一个报价= 51.
所以我的问题是:
1 - 难道我应该如何使用autofixture的方式?
2 - 是否有可能改善我在我的例子中使用自动混合的方式?
+1 @Gui和其他人马克太客气了,但他的[PluralSight Advanced Unit Testing](http://pluralsight.com/training/courses/TableOfContents?courseName=advanced-unit-testing)当然是chock充满了这种善良。值得付出,但更好,他们有一个免费试用,我不能想到一个更好的课程使用它(当然[外部在测试驱动开发](http://pluralsight.com/training/Courses/TableOfContents/外部在tdd)是接近第二) –
@马克西曼感谢您的评论马克。我同意你的测试肯定更具可读性。我打算提出一些更多的问题,但是你的答案非常完整,每次我重新阅读你的答案时都会回答我的每一个问题。 Omg,你可能是单元测试的神。 – Gui
如何为测试项目中定义的'WithClose','WithLimit' *添加扩展方法,而不是将它们添加为实例方法? (现在在C#6中,他们甚至不需要处于静态类) – 2016-02-07 21:21:27