- VS使用[TestClass]和[TestMethod]标识单元测试代码
- MSTest测试框架中,为Assert类设计了一系列的方法实现“断言”
测试期望抛出的异常
public int Sum(int from, int to)
{
if (from > to)
{
throw new ArgumentException("参数from必须小于to");
}
int sum;
for (int i = from; i<= to; i++)
{
sum += i;
}
return sum;
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void SumExceptionTest()
{
target.Sum(100, 50);
}
public const String AgeErrorString = "生日必须小于当前日期";
public int CaculateAge(DateTime Birthday)
{
if (DateTime.Now < Birthday)
{
throw new ArgumentOutOfRangeException(AgeErrorString);
}
return DateTime.Now.Year - Birthday.Year;
}
[TestMethod]
public void CalculateAgeOutOfRangeTest()
{
try
{
MyClass target = new MyClass();
target.Calculate(DateTime.Now.AddDays(1));
}
catch (ArgumentOutOfRangeException e)
{
StringAssert.Contains(e.Message, MyClass.AgeErrorString);
}
Assert.Fail("No exception was thrown");
}
每次测试前执行特定的代码
- [TestInitialize]
- [TestCleanup]
所有测试前/后执行代码
- [ClassInitialize]
- [ClassCleanup]