1
我需要編寫單元測試以測試輸入是否爲有效貨幣值。我嘗試了幾種方法,但我不認爲這是測試貨幣價值的正確方法。C#單元測試貨幣驗證
測試用例:
namespace validationUnitTest
{
// Validation rule for checking if the input is a valid currency value
public class CurrencyValidationRule: ValidationRule;
{
private static ValidationRule validationRule;
/// Singleton instance of this <see cref="ValidationRule"/>
public static ValidationRule Instance { get { return validationRule ?? (validationRule = new CurrencyValidationRule()); } }
// performs validation checks on a value
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value is double) return ValidationResult.ValidResult;
string stringValue = value as string;
double result;
return string.IsNullOrEmpty(stringValue) || double.TryParse(stringValue, NumberStyles.Currency, cultureInfo, out result) ? ValidationResult.ValidResult : new ValidationResult(false, "Value must be an number");
}
}
}
單位測試:
namespace validationUnitTest.Tests
{
[TestClass()]
public class CurrencyValidationRuleTests
{
[TestMethod()]
public void ValidateTest()
{
var test = new CurrencyValidationRule();
var expected = new ValidationResult(true, true);
var actual = test.Validate("0", null);
Assert.AreEqual(expected.ErrorContent, actual.ErrorContent);
Assert.AreEqual(expected.IsValid, actual.Isvalid);
Assert.AreEqual(expected.GetHashCode(), actual.GetHashCode());
}
}
}
,我應該如何開始我的單元測試什麼想法,或者我應該是什麼搜索?我需要一些起點。任何事情都非常感謝。
你能舉個例子嗎? – Dnguy025
我做了什麼var actual = test.Validate(「0」,null);這樣對嗎? – Dnguy025
在上面的代碼中,您可以調用您的方法並獲得實際結果並與預期結果進行比較。檢查這個鏈接:https://xunit.github.io/ –