Java and Junit initialization order

initialization order

class BaseClass {


  static String myBaseStaticText=basesay("base static");


    String myBaseText = basesay("base local field");


    public BaseClass() {
        basesay("base constructor");
    }


    static String basesay(String text) {
        System.out.println(text);
        return text;
    }
}


public class InitializationTest extends BaseClass {


    static String myStaticText = say("static");


    String myText = say("local field");


    public InitializationTest() {
        say("constructor");
    }


    public static void main(String[] args) {
        new InitializationTest();
    }


    static String say(String text) {
        System.out.println(text);
        return text;
    }
}

Output:

base static
static
base local field
base constructor
local field
constructor

JUnit

public class MyJunitTest {

    String text = staticSay("field");
   static String staticText = staticSay("static field");

    public MyJunitTest() {
    System.out.println("constructor");
    }

    public MyJunitTest(String text) {
        System.out.println("constructor: " + text);
    }

    @Test
        public void myTestCase1() {
    }

    @Test
        public void myTestCase2() {
    }

    String say(String text) {
        return staticSay(text);
    }

    static String staticSay(String text) {
        System.out.println(text);
        return text;
    }
}

Output:

static field
field
constructor
field
constructor

Instantiate class
public class InitializeClass {

    public static void main(String[] args) throws ...


        Class cl =
            Class.forName(MyJunitTest.class.getName());
        Constructor defConstr = cl.getConstructor();
        defConstr.newInstance();
        Constructor constr =
            cl.getConstructor(String.class);
        MyJunitTest instance =
        (MyJunitTest) constr.newInstance("with string");
        instance.say("method with string");
        Method[] methods =
            cl.getDeclaredMethods();
        for (Method method : methods) {
            Test annotation =
                method.getAnnotation(Test.class);
            if (annotation != null) {
                System.out.println("Method " +
                "with @Test: " + method.getName());
            }
        }
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s