5

I have some Java code that I am unit testing using JUnit, running inside Eclipse (Neon). It so happens that some code under test has a bug in it, causing it to enter an infinite loop. The JUnit run then, of course, does not finish. How do I kill the test run?

The button for stopping the test run ("Stop JUnit Test Run") does not work well: the GUI seems to think that it has stopped the test run, but a look at the CPU activity (using top, for example), shows that a Java thread is still running. I can kill the thread myself by sending it a kill signal. But that seems a kludge and is inconvenient. Is there a better way, available within Eclipse itself?

Raedwald
  • 46,613
  • 43
  • 151
  • 237

3 Answers3

7

Kill it from the console view, using the red button. This stops the process.

enter image description here

Stopping it from the junit view only asks it to stop.

Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171
5

You can handle such things with JUnit by specifying a time-out within the @Test annotation. For example:

// Simple test-case which will always fail with time-out
@Test(timeout = 1000 * 60) throws Exception // 60 seconds 
public void testSomething() {
    for (int i = 0; i < 100; i++) {  // 100 seconds
        Thread.sleep(1000);
    }
}

If your test method doesn't finish on time, then JUnit will interrupt it and report a test failure. For the example above it will be:

java.lang.Exception: test timed out after 60000 milliseconds
    at java.lang.Thread.sleep(Native Method)
    at my.package.Test1.testSomething(Test1.java:12)
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
  • Useful if you anticipate a failure of a particular test *might* cause an infinite loop. Not so useful if you have no good reason to suspect that, or a subsequent attempted re-factoring introduces an infinite loop. – Raedwald Jun 27 '17 at 11:58
  • @Raedwald Well, I would turn around your reasoning and annotate *every* test method with `@Test(timeout=60000)` (or some other arbitrarily high timeout) even if I do *not* have any reason to expect an infinite loop. – Thomas Fritsch Jun 27 '17 at 12:18
  • Adding that to *every* test is a code smell, I think. – Raedwald Jun 27 '17 at 14:34
  • @Raedwald Yes indeed, it looks smelly. A better way would be to set a default time-out as described in this [answer to "Set JUnit timeout in eclipse"](https://stackoverflow.com/questions/4097821/set-junit-timeout-in-eclipse/13600361#13600361). – Thomas Fritsch Jun 27 '17 at 16:16
0

First, try Matthew Farwell's answer. If that doesn't work then you have to go to your processes running (ctrl+shift+esc on windows, then processes tab) and select the java.exe task, then end process. In the event you ever need to kill eclipse, it's javaw.exe

sparks
  • 736
  • 1
  • 9
  • 29