Nunit否定测试预期的例外情况

时间:2013-10-02 07:11:02

标签: c# visual-studio-2012 nunit .net-4.5

我有一个类,我检查索引或字符串的长度。我想写一个Nunit Negative Test:

  • 如果字符串的长度超出范围,则Nunit测试为真。或者第一个索引是数字“假”Nunit Test是真的。

我尝试了什么:

我的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超出范围,则测试必须为绿色也是如此。 我如何使用测试是真的?

THX

1 个答案:

答案 0 :(得分:2)

使用Assert.Throws()

string keyHasLengthOf24 = "KM6163-33583-01125-68785";

var ex = Assert.Throws<Exception>(() => keymanager.SetKey(keyHasLengthOf24));

Assert.That(ex.Message, Is.EqualTo("Index Out of Range "));

有关详细信息,请参阅this SO answer