Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fail a test that is stuck in an infinite loop?

Tags:

I have some code that produces an infinite loop. Now I need to write a test that will fail after about 200ms. 200ms will indicate that the code is in the infinite loop.

For example:

public void CodeUnderTest() {    while(true)    {     } }  
like image 951
O.O Avatar asked Aug 27 '12 16:08

O.O


People also ask

How do you get out of an infinite loop?

You can press Ctrl + C .

Can you get stuck in an infinite loop?

In multi-threaded programs some threads can be executing inside infinite loops without causing the entire program to be stuck in an infinite loop. If the main thread exits all threads of the process are forcefully stopped thus all execution ends and the process/program terminates.

What causes infinite loop error?

An infinite loop error describes a technical glitch that forces your computer to repeat the same actions over and over again. For example, you just restarted your device after you installed the latest OS version. But instead of booting up, your computer keeps on restarting.

Is an infinite loop an error?

What is an Infinite Loop? An infinite loop occurs when a condition always evaluates to true. Usually, this is an error. For example, you might have a loop that decrements until it reaches 0.


2 Answers

When using MSTest you can use an attribute

[TestMethod] [Timeout(200)] 

See How to force tests to stop running

You can set time limits with which the execution of a test or a test run will comply. You might need to do this, for example, if you work in a test lab and need a test run to complete by a certain time of day.

Another scenario for the use of time limits is that of non-responsive code.

like image 172
P.Brian.Mackey Avatar answered Oct 04 '22 21:10

P.Brian.Mackey


what about:

Task.Create(CodeUnderTest).Wait(TimeSpan.FromSeconds(1)); 

or:

Task.Factory.StartNew(CodeUndertest).Wait(TimeSpan.FromSeconds(1)); 

or:

Task.Factory.StartNew(() => CodeUndertest(arg1,arg2,arg3...)).Wait(TimeSpan.FromSeconds(1)); 
like image 24
TheHe Avatar answered Oct 04 '22 22:10

TheHe