[C#] [NUnit] TestCase Attribute 為什麼不能使用 decimal 型別

  • 51
  • 0

最近在使用 NUnit framework 寫單元測試時,遇到很詭異的情況
想要做個筆記,紀錄一下

以下使用的範例參考自官方文件

在寫單元測試時,可以使用 TestCase Attribute 來輸入不同數據來測試
以減少大量重複的程式碼
像是這樣:

[TestCase(2, 3, 6)]
[TestCase(2, 2, 4)]
[TestCase(2, 4, 8)]
public void MultiplyTest(int n, int d, int q)
{
    Assert.That(n / d, Is.EqualTo(q));
}

但最近在工作中,遇到的問題是當我的 TestCase Attribute 有兩個以上的參數,且有一個為 decimal
像是這樣:

[TestCase(2, 3m, 6)]
[TestCase(2, 2m, 4)]
[TestCase(2, 4m, 8)]
public void MultiplyTest(int n, decimal d, int q)
{
    Assert.That(n * d, Is.EqualTo(q));
}

就會得到錯誤訊息,整個測試都沒辦法跑

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

後來在發現也有其他人遇到一樣的問題
原來不是 NUnit 框架的問題,是受到 C# Attribute parameter types 所限制

  • One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.

因為裡面沒有支援 decimal 使用於 attribute parameter,所以 IDE 才會直接噴錯給你看
這個雷還真的是沒有遇過,不會注意到的小地方
隨手筆記一下囉!


微軟官網 Attribute parameter types 的定義 

stackoverflow