Saturday, August 9, 2014

Unit Testing : [ExpectedException]

Hi All,

In this post I’ll explain what you need to do if you have to ensure that a particular exception must be thrown by your C# code.

The reason why I am writing this post is that some people mistakenly use keyword ExpectedException as given below:

[TestMethod]
[ExpectedException(typeof(ApplicationException), "Game has already Concluded, Start new Game !")]
public void FirstTwoRows()
{
  GameEngine ttt = new GameEngine();
  Assert.IsTrue(ttt.RecordMove('a', 3), "This is not a winning move");
  //Following line should throw Application Exception
  Assert.IsFalse(ttt.RecordMove('b', 6), "This is not a winning move");
}

Q: What is wrong with this code?
A: This test method will not fail if you get the specified Exception, but it will also pass when you don’t get it at all.

Q: So, whats the fix?
A:  You also need to add Assert.Fail after the line where you are expecting the exception.

[TestMethod]
[ExpectedException(typeof(ApplicationException), "Game has already Concluded, Start new Game !")]
public void FirstTwoRows()
{
  GameEngine ttt = new GameEngine();
  Assert.IsTrue(ttt.RecordMove('a', 3), "This is not a winning move");
  //Following line should throw Application Exception
  Assert.IsFalse(ttt.RecordMove('b', 6), "This is not a winning move");
  Assert.Fail("Above line should have thrown Exception of given type");
}
 I hope this small change will save lot of time for you and make your Test driven Development even better.

Namaste (Greetings)
Anugrah Atreya




No comments: