Can you guess the output? junit and initialization

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.

2 Comments

  1. test test comment

    admin
    Posted February 12, 2009 at 9:39 pm | Permalink
  2. shoot, sorry, somehow comments are all lost for this post! I hope this is not the only affected post. and no idea what happened :(

    Posted June 4, 2009 at 10:09 am | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Anti-Spam Protection by WP-SpamFree