Unit test and State-based testing
Source: The art of unit testing with examples in .NET, Roy Osherove
http://www.amazon.com/Art-Unit-Testing-Examples-Net/dp/1933988274/ref=sr_1_1?ie=UTF8&s=books&qid=1267086529&sr=1-1
Chapter 2 A first unit test
1. 簡單的單元測試範例
(1) 受測類別
先寫好程式, 等待之後測試
public class SimpleParser {
public int ParseAndSum( string numbers) {
if (numbers.Length == 0)
return 0;
if ( !numbers.Contains(",") ) {
return int.Parse(numbers);
}
else {
throw new InvalidOperationException( "I can only handle 0 or 1 numbers for now!");
}
}
}
(2) 測試程式
calss SimpleParserTests {
public static void TestReturnsZeroWhenEmptyString() {
try {
SimpleParser p = new SimpleParser();
int result = p.ParseAndSum(string.Empty);
if (result != 0) {
Console.WriteLine("Parse and sum should have returned 0 on an empty string!");
}
}
catch ( Exception e) {
Console.WriteLine(e);
}
}
}
(3)用console mode來驅動測試
public static void Main(string[] args) {
try {
SimpleParserTests.TestReturnsZeroWhenEmptyString();
}
catch( Exception e ) {
Console.WriteLine(e);
}
}
2. State-based testing
(1) 又稱state verification
(2) determine whether the exercised method worked correctly by examining the state of the system under test and its collaborators(dependencies) after the method is exercised
==> 所以重點在檢查受測程式和相關者的狀態是否正確
(3) 範例:
public class Log Analyzer {
private bool wasLastFileNameValid;
pubic bool WasLastFileNameValid {
get { return wasLastFileNameValid; }
set { wasLastFileNameValid = value; }
}
public bool IsValudLogFileName( string fileName ) {
if ( !fileName.ToLower().EndsWith(".slf") ) {
wasLastFileNameValid = false;
return false;
}
// save state of result for later assertions
wasLastFileNameValid = true;
return true;
}
}
[Test]
public void IsValidLogFileName_ValidName_RemembersTrue() {
LogAnalyzer log = LogAnalyzer();
log.IsValidLogFileName("somefile.slf");
// 藉由檢查受測類別的狀態來確認測試是否成功
// 而不是檢查受測函式的傳回值
Assert.IsTrue(log.WasLastFileNameValid);
}
留言列表