【发布时间】:2013-10-08 12:38:50
【问题描述】:
我有一个检查索引或字符串长度的类。我想写一个 Nunit Negative Test:
- 如果字符串的长度超出范围,则 Nunit 测试为真。或者第一个索引是数字“假”,Nunit 测试为真。
我的尝试:
我的 CheckKeyClass:
public void SetKey(string keyToAnalyse)
{
Line = new string[keyToAnalyse.Length];
int nummeric;
bool num;
if (Line.Length == 0 || Line.Length < 24)
{
throw new Exception("Index Out of Range " + Line.Length);
}
// Ist Product a Character
num = int.TryParse(Line[0], out nummeric);
if (!num)
{
if (Line[0] == "K")
{
Product = 0;
}
}
else
{
throw new Exception("The Productnumber is not right: " + Line[0] ". \nPlease give a Character.");
}
}
我的 Nunit 测试:
[Test]
public void NegativeTests()
{
keymanager.SetKey("KM6163-33583-01125-68785");
// Throws<ArgumentOutOfRangeException>(() => keymanager.Line[24]);
}
// ExpectedException Handling
public static void Throws<T>(Action func) where T : Exception
{
var exceptionThrown = false;
try
{
func.Invoke();
}
catch (T)
{
exceptionThrown = true;
}
if (!exceptionThrown)
{
throw new AssertFailedException(String.Format("An exception of type {0} was expected, but not thrown", typeof(T)));
}
}
因此,如果 Line.length 超出范围,则测试必须为绿色也是如此。 我如何使用测试为真?
谢谢
【问题讨论】:
-
可以不用自带的
Assert.Throws<T>吗?
标签: c# visual-studio-2012 nunit .net-4.5