測試總管
本系列文章不是基礎教學文件,基本東西就不說明了。下圖是Visual Studio的測試總管畫面。總計18單元測試項目(可能還會增加),是針對SDK所提供的函數進行測試。
測試專案
雖然現階段測試僅針對SQLite(TesterForSqlite.cs),但實際上所提供的服務函數各家資料庫都是一樣的(DataBaseServiceTests.cs),主要差別是在SQL產生器的部分。Models目錄就是定義好的模型。
模型定義
所有資料表類別,都需要繼承TableDefBaseModel類別。只要單純宣告此類別所擁有的屬性即可。PersonTable類別為例。
public class PersonTable : TableDefBaseModel
{
public string? Name { get; set; }
public int Age { get; set; }
}
{
public string? Name { get; set; }
public int Age { get; set; }
}
TableDefBasedModel類別由資料表類別來繼承,提供幾個重要的共通欄位。
public abstract class TableDefBaseModel
{
protected TableDefBaseModel(string? userName = null)
{
CreatedDate ??= DateTime.UtcNow;
LastModifyDate = DateTime.UtcNow;
CreatorName = userName;
}
[]
[]
public long Id { get; set; }
[]
public DateTime? CreatedDate { get; set; }
public DateTime? LastModifyDate { get; set; }
public string? CreatorName { get; set; }
}
為了後續各項服務能方便使用,補了一個Extension Function。至於用途如何,在講解測試函數時便可知。public static class TableDefBaseModelExtension
public static class TableDefBaseModelExtension
{
public static IEnumerable<KeyValuePair<string, object?>> GetKeyValuePairs(this TableDefBaseModel source, bool withKey = false)
{
var properties = source.GetType().GetProperties();
List<KeyValuePair<string, object?>> target = [];
foreach (var p in properties)
{
if (p.Name == "Id" && !withKey) continue;
target.Add(new(p.Name, p.GetValue(source)));
}
return target;
}
}
public class TesterForSqlite: DataBaseServiceTests
{
private const string connString = @"Data Source=C:\temp\Test.db;";
public TesterForSqlite() : base(MainService.UseSQLite(connString))
{
}
}
針對不同的資料庫提供者,建立不同測試類別。測試類別都繼承DataBaseServiceTests,因為所需要測試的函數幾乎一樣,這邊只需要定義資料庫連線字串,以及告知父類別這個測試類別是真的那個資料庫提供者。
{
protected TableDefBaseModel(string? userName = null)
{
CreatedDate ??= DateTime.UtcNow;
LastModifyDate = DateTime.UtcNow;
CreatorName = userName;
}
[]
[]
public long Id { get; set; }
[]
public DateTime? CreatedDate { get; set; }
public DateTime? LastModifyDate { get; set; }
public string? CreatorName { get; set; }
}
為了後續各項服務能方便使用,補了一個Extension Function。至於用途如何,在講解測試函數時便可知。public static class TableDefBaseModelExtension
public static class TableDefBaseModelExtension
{
public static IEnumerable<KeyValuePair<string, object?>> GetKeyValuePairs(this TableDefBaseModel source, bool withKey = false)
{
var properties = source.GetType().GetProperties();
List<KeyValuePair<string, object?>> target = [];
foreach (var p in properties)
{
if (p.Name == "Id" && !withKey) continue;
target.Add(new(p.Name, p.GetValue(source)));
}
return target;
}
}
測試類別
[]public class TesterForSqlite: DataBaseServiceTests
{
private const string connString = @"Data Source=C:\temp\Test.db;";
public TesterForSqlite() : base(MainService.UseSQLite(connString))
{
}
}
針對不同的資料庫提供者,建立不同測試類別。測試類別都繼承DataBaseServiceTests,因為所需要測試的函數幾乎一樣,這邊只需要定義資料庫連線字串,以及告知父類別這個測試類別是真的那個資料庫提供者。
沒有留言:
張貼留言