1

我有一个检查索引或字符串长度的类。我想写一个 Nunit 否定测试:

  • 如果字符串的长度超出范围,则 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 Out of Range 测试必须是绿色的也是如此。我如何使用测试是真实的?

谢谢

4

1 回答 1

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 "));

有关更多详细信息,请参阅此 SO 答案

于 2013-10-02T07:14:20.183 回答