【问题标题】:Nunit Negative Tests Expected ExceptionNunit 否定测试预期异常
【发布时间】: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 超出范围,则测试必须为绿色也是如此。 我如何使用测试为真?

谢谢

【问题讨论】:

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


【解决方案1】:

使用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

【讨论】:

    猜你喜欢
    • 2011-07-31
    • 2011-03-25
    • 1970-01-01
    • 2019-01-23
    • 2014-08-14
    • 2013-03-16
    • 1970-01-01
    • 2012-04-05
    • 2015-08-09
    相关资源
    最近更新 更多