2

I'm developing some JUnit tests for my application.

When I run the tests in Eclipse I get the result for each test and the time spent, as you can see in the image below.

enter image description here

But how is it computed? Does it include the time spent in the @Before and @After methods for each test or does it take into account only the time spent in the @Test method?

Thank you

gvdm
  • 3,006
  • 5
  • 35
  • 73
  • 1
    Why not test it out? In methods annotated with `@Before` or `@After`, execute a long running task, see if it affects the results. – Vince Apr 19 '16 at 16:09
  • 2
    eclipse is not computing anything. The junit test runner is performing the computations. it seems likely that the `@Before` and `@After` methods are not included in the duration of a given test. – DwB Apr 19 '16 at 17:25
  • I added a Thread.sleep(5000); in the Before method and the final time of the test is more than 7 seconds. I think that this means that the spent time takes into account also the Before and After methods...isn't it? – gvdm Apr 20 '16 at 07:16
  • 1
    Use also System.currentTimeMillis() at the begining and at the end of your test method (excluding @Before and @After) if you want to know exactly the time spent by your test – Jorge Apr 20 '16 at 07:28
  • Or maybe the Stopwatches http://stackoverflow.com/questions/14892125/what-is-the-best-practice-to-determine-the-execution-time-of-the-bussiness-relev – gvdm Apr 20 '16 at 08:13

1 Answers1

0

There is, in JUnit, intreface called TestListener. JUnit provides some implementations that were attached to each test run. One of those implementations is internal Listener class in Result class. It calculates time in that way

public void testRunStarted(Description description) throws Exception {
    startTime.set(System.currentTimeMillis());
}

@Override
public void testRunFinished(Result result) throws Exception {
    long endTime = System.currentTimeMillis();
    runTime.addAndGet(endTime - startTime.get());
}

Code taken from org.junit.runner.Result JUnit 4.12.

After calculation JUnit publish "report" that contains all Results of tests. IDEs like Eclipse or Idea attach to test JUnit they implementations of TestListener that could parse&show "report". Finally listeners from IDE send message to IDE window and you could see test result and time.

Koziołek
  • 2,791
  • 1
  • 28
  • 48