我需要编写一个单元测试来测试输入是否是有效的整数值。我已经尝试了几种方法,但我认为这不是测试货币价值的正确方法。
测试用例:
namespace validationUnitTest
{
// Validation rule for checking if the input is a valid integer value
public class IntegerValidationRule: ValidationRule;
{
private static ValidationRule validationRule;
/// Singleton instance of this <see cref="ValidationRule"/>
public static ValidationRule Instance { get { return validationRule ?? (validationRule = new IntegerValidationRule()); } }
// performs validation checks on a value
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value is long) return ValidationResult.ValidResult;
string stringValue = value as string;
Long result;
return string.IsNullOrEmpty(stringValue) || long.TryParse(stringValue, NumberStyles.Integer, cultureInfo, out result) ? ValidationResult.ValidResult : new ValidationResult(false, "Value must be an integer");
}
}}
单元测试:
namespace validationUnitTest.Tests
{
[TestClass()]
public class IntegerValidationRuleTests
{
[TestMethod()]
public void ValidateTest()
{
var test = new IntegerValidationRule();
var expected = new ValidationResult(true, 3);
var actual = test.Validate("0", null);
Assert.AreEqual(expected.ErrorContent, actual.ErrorContent);
Assert.AreEqual(expected.IsValid, actual.Isvalid);
Assert.AreEqual(expected.GetHashCode(), actual.GetHashCode());
}
}}
你知道我应该如何开始我的单元测试吗,或者我应该搜索什么?我需要一些起点。任何事情都是万分感激的。
发布于 2016-10-05 01:00:44
首先,您的double方法只检查数字是否是一个有效的整数,而不是检查它是否实际上是一个有效的整数。如果值是双精度值,它也会返回true,这不是您要求它做的事情。您应该利用int.TryParse(string, int) method.
我会重写validate方法,使其看起来像这样:
public override ValidationResult Validate(string value)
{
int number;
bool isValid = int.TryParse(value, out number);
return isValid
? ValidationResult.ValidResult
: new ValidationResult(false, "Value must be an integer");
}至于您的单元测试,我只接受一些不同的字符串值,并断言它们是否有效。您不需要为您的“期望值”运行该方法,因为您已经知道您的测试值是否为有效的整数。
var actual = test.Validate("0");
Assert.IsTrue(actual.IsValid);
actual = test.Validate("foo");
Assert.IsFalse(actual.IsValid);
// Repeat ad nauseum with different valueshttps://stackoverflow.com/questions/39857704
复制相似问题