On đội của tôi mà bị khóa vào sử dụng khuôn khổ MS thử nghiệm, chúng tôi đã phát triển một kỹ thuật mà chỉ dựa vào Anonymous Các loại để giữ một mảng dữ liệu thử nghiệm và LINQ lặp lại và kiểm tra từng hàng. Nó không đòi hỏi thêm các lớp hoặc khung công tác bổ sung nào, và có xu hướng khá dễ đọc và dễ hiểu. Nó cũng dễ thực hiện hơn nhiều so với các bài kiểm tra dựa trên dữ liệu bằng cách sử dụng các tệp bên ngoài hoặc một cơ sở dữ liệu được kết nối.
Ví dụ, nói rằng bạn có một phương pháp mở rộng như thế này:
public static class Extensions
{
/// <summary>
/// Get the Qtr with optional offset to add or subtract quarters
/// </summary>
public static int GetQuarterNumber(this DateTime parmDate, int offset = 0)
{
return (int)Math.Ceiling(parmDate.AddMonths(offset * 3).Month/3m);
}
}
Bạn có thể sử dụng và hàng loạt các loại Anonymous kết hợp để LINQ để viết một bài kiểm tra như thế này:
[TestMethod]
public void MonthReturnsProperQuarterWithOffset()
{
// Arrange
var values = new[] {
new { inputDate = new DateTime(2013, 1, 1), offset = 1, expectedQuarter = 2},
new { inputDate = new DateTime(2013, 1, 1), offset = -1, expectedQuarter = 4},
new { inputDate = new DateTime(2013, 4, 1), offset = 1, expectedQuarter = 3},
new { inputDate = new DateTime(2013, 4, 1), offset = -1, expectedQuarter = 1},
new { inputDate = new DateTime(2013, 7, 1), offset = 1, expectedQuarter = 4},
new { inputDate = new DateTime(2013, 7, 1), offset = -1, expectedQuarter = 2},
new { inputDate = new DateTime(2013, 10, 1), offset = 1, expectedQuarter = 1},
new { inputDate = new DateTime(2013, 10, 1), offset = -1, expectedQuarter = 3}
// Could add as many rows as you want, or extract to a private method that
// builds the array of data
};
values.ToList().ForEach(val =>
{
// Act
int actualQuarter = val.inputDate.GetQuarterNumber(val.offset);
// Assert
Assert.AreEqual(val.expectedQuarter, actualQuarter,
"Failed for inputDate={0}, offset={1} and expectedQuarter={2}.", val.inputDate, val.offset, val.expectedQuarter);
});
}
}
Khi sử dụng kỹ thuật này rất hữu ích khi sử dụng một tin nhắn được định dạng bao gồm dữ liệu đầu vào trong Assert để giúp bạn xác định hàng nào làm cho thử nghiệm thất bại.
Tôi đã viết blog về giải pháp này với nhiều nền và chi tiết hơn tại AgileCoder.net.
Đáng buồn thay, DaTest dường như chỉ hoạt động với VS2008. –
http://code.google.com/p/datest/wiki/DaTest –
Bản sao có thể có của [Cách chạy phương pháp thử nghiệm với nhiều thông số trong MSTest?] (Http://stackoverflow.com/questions/9021881/how -to-run-a-test-method-với-nhiều-tham số-trong-mstest) – Rob