1

I have a class that I check the index or the length of the string. And I want to write a Nunit Negative Test:

  • if the length of the string Out of Range the Nunit Test is true. Or the first index is digit "false" the Nunit Test is true.

What i try:

My 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.");
  }
}

My Nunit Test:

[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)));
  }
}

So if the Line.length Out of Range the Test must be green also true. How do I use that the Tests is true?

thx

1

1 Answer 1

2

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

See this SO answer for further detail.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.