How to unit test a method that runs into an infinite loop for some input?

Shankar Raju picture Shankar Raju · May 11, 2011 · Viewed 12.9k times · Source

This question just occurred to my mind and I want to ask this here.

The case is intentional, I just write a loop which runs infinitely. How do I go about unit testing it?

I ask this because, this situation may occur anywhere in the code. Say my method delegates to several other methods, and I want to know

  • How it ran into an infinite loop
  • What set of input caused it
  • Call to which method (from this method) has caused this

I have no code written for this. The question is purely for knowledge sake as to what to do if this situation arises in future. Please respond.

Answer

k3b picture k3b · May 11, 2011

How to unit test a method that runs into an infinite loop for some input?

You can test the nearly opposite: "How to unit test a method so that the method will not run longer than Xxxx milliseconds for some input". If this test fails you may have found a candidate with an infinite loop.

NUnit 2.5 has a TimeoutAttribute that makes a test fail if the test takes longer than the given amount of milliseconds.