0

Can someone explain how my Junit passed successfully with below singleton implementation

EagerInitializations.java (singleton)

package com.r.patterns.design;

public class EagerInitializations {

    private  final String NAME="SINGELTON";

    private static final EagerInitializations INSTANCE=CreateEagerInitializations();

    private static EagerInitializations CreateEagerInitializations(){

        System.out.println("step constructor");
        return new EagerInitializations();
    }

    public final static EagerInitializations getInstance(){
        System.out.println("step INSTANCE");
        return INSTANCE;

    }

    public String getNAME() {
        return NAME;
    }
}

EagerInitializationsTest.java (JUnit test)

package com.r.patterns.design;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class EagerInitializationsTest {

    @Test(expected = ClassNotFoundException.class)
    public void testSingleton() throws ClassNotFoundException  {

        Class.forName("EagerInitializations");
        EagerInitializations EI=null;

        assertEquals(EI.getNAME(),new String("SINGELTON"));

    }

}
0

1 Answer 1

1

The only way that this test can pass successfully is if the call to

Class.forName("EagerInitializations");

throws a ClassNotFoundException, because you are specifying that this exception is expected in the @Test annotation.

The assertion in the last line of the test is not evaluated because the exception is caught by the JUnit runner, causing the test to pass before that line is reached.

I would suggest setting a breakpoint in your test and debugging through the code in your IDE to better understand what is happening.

1
  • 1
    No magic or need to debug there, since the class is actually in package com.r.patterns.design and not in the default package. Class.forName expects the fully qualified name of the class, which here would be com.r.patterns.design.EagerInitializations Commented Mar 13, 2016 at 15:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.