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




Big O Notation : Algorithm Performance

Big-O-Notation is used to measure and express the relative representation of the complexity of an algorithm:

 

Did you ever tried to understand why :

·         Bubble Sort is O( n square )

·         Quick Sort is O( n log n)

or you just remember it by heart and don’t know what’s hiding behind these names/values J

 

Below given are two best explanations I found in a quick search:

http://stackoverflow.com/questions/2307283/what-does-olog-n-mean-exactly

http://stackoverflow.com/questions/487258/plain-english-explanation-of-big-o/487278#487278

 

They both use example of Telephone Book and make it so simple to understand the whole thing.

If you understand the Telephone Book example then I guarantee you that you will be able to tell the performance of any algorithm in a quick moment without referring its documentation.

 

Namaste (Greetings)

Anugrah Atreya