Ahti Kitsik
Building tools with Python, Java, Go, JS. For enquiries email inbox@ahtik.com

writings biography

Can you guess the output? junit and initialization

15 Dec 2008 by @ahtik

Can you guess the output without running the code?

The relation to Eclipse is simply the fact that big part of eclipse.org is a great example of good test coverage built on top of jUnit. Plus, it was literally pulling my hair out in one of the eclipse-related testing-suites.

I stepped into this a few years ago while bug-fighting a test class that had unexpected initialization.

Pretty sure that many of you know the answer but definitely fun outcome!

As everyone can simply run this snippet yourself I won't delay approving comments, I'll just accept them whenever I get a free moment. This comment system here has captcha but additionally all comments must be approved manually.

import junit.framework.TestCase;
public class MyTest extends TestCase {
private static int count = 0;

{ count++; }

public MyTest() {count++;}

public void test1() { System.out.print(count); }
public void test2() { System.out.print(count); }
public void test3() { System.out.print(count); }

}

I'm sure some of us don't always take this behavior into account :)

After figuring this out, SPECIAL fun is a bit modified case:

import junit.framework.TestCase;
public class MyTest extends TestCase {
private static int count = 0;

{ count=count*2; }

public MyTest() { count++; }

public void test1() { System.out.print(count); }
public void test2() { System.out.print(count); }
public void test3() { System.out.print(count); }
}

For this last snippet I think without running it you won't figure it out :) At least I didn't..

UPDATE: Decent in-depth hi-tech doc about java init http://www.artima.com/designtechniques/initialization7.html

UPDATE2: Correct answers were 666 and 777.

@ahtik is on twitter!