ganesh r
ganesh r

Reputation: 51

Java Singleton design pattern

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"));

    }

}

Upvotes: 0

Views: 75

Answers (1)

jamess
jamess

Reputation: 158

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.

Upvotes: 1

Related Questions