我运行(或调试)所有单元测试时,我的单元测试失败了,但是当我运行单元测试时却没有。
测试:
[TestMethod]
public void IsFullTest()
{
Assert.IsTrue(WeekPeriod.IsFullWeek);
Assert.IsTrue(YearPeriod.IsFullYear);
Assert.IsTrue(DayPeriod.IsFullDay);
Assert.IsTrue(MonthPeriod.IsFullMonth);
Assert.IsTrue(QuarterPeriod.IsFullQuarter);
Assert.IsFalse(MonthPeriod.IsFullWeek);
Assert.IsFalse(DayPeriod.IsFullYear);
Assert.IsFalse(WeekPeriod.IsFullDay);
Assert.IsFalse(QuarterPeriod.IsFullMonth);
Assert.IsFalse(YearPeriod.IsFullQuarter);
}
这些句点在构造函数中实例化:
public PeriodTest()
{
YearPeriod = new Period(new DateTime(2014, 5, 1), new DateTime(2015, 5, 1));
MonthPeriod = new Period(new DateTime(2014, 5, 1), new DateTime(2014, 6, 1));
DayPeriod = new Period(new DateTime(2014, 5, 8), new DateTime(2014, 5, 9));
WeekPeriod = new Period(new DateTime(2014, 5, 5), TimeSpan.FromDays(7));
QuarterPeriod = new Period(new DateTime(2014, 5, 1), new DateTime(2014, 8, 1));
}
第一次断言失败; Period.IsFullWeek:
public bool IsFullWeek
{
get
{
return !HasTime && (Start != null) && (Start.Value.DayOfWeek == CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek) && (Length == TimeSpan.FromDays(7));
}
}
有没有办法发现测试在运行所有内容时失败,而不是运行独奏?
其他信息:
我调试了特定的测试(通过调试全部)并且它正在接收它的'数据正确。 IsFullWeek方法生成错误的值,这就是断言失败的原因。但是,它仅在运行此一个测试(运行选定)时生成正确的值。
答案 0 :(得分:2)
你真的必须将unittest重写为AAA:Arrange-Act-Assert
这将帮助您找出测试失败的原因。此时你必须启动调试器,甚至看到测试因为顺序而不稳定。相互交互的测试不会让您清楚地了解代码的错误。为您抽样单元测试:
[TestMethod]
public void WeekTest()
{
//Arrange
Period weekPeriod = new Period(new DateTime(2014, 5, 5), TimeSpan.FromDays(7));
//Act
bool isweek = weekPeriod.IsFullWeek;
//Assert
Assert.IsTrue(isweek );
}
答案 1 :(得分:1)
我明白了。可能是.Net Framework中的一个错误,但这就是:
正如您在IsFullWeek中所看到的,它检查Start.Value.DayOfWeek是否是FirstDayOfWeek:
CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek
在此查看声明:
public DayOfWeek FirstDayOfWeek
{
get
{
// FirstDayOfWeek is always set in the Calendar setter.
return ((DayOfWeek)firstDayOfWeek);
}
set {
VerifyWritable();
if (value >= DayOfWeek.Sunday && value <= DayOfWeek.Saturday) {
firstDayOfWeek = (int)value;
} else {
throw new ArgumentOutOfRangeException(
"value", String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"),
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
}
}
这里需要日历设置;然后是指定的第一天。选择运行时,第一天是星期一,在我的日历设置中设置。当所有第一天的运行突然变为星期六时,我的测试失败,因为周期从星期一+ 7天开始。
所以我知道为什么它会失败,为什么突然改变几天是另一个问题。