Quest P
Quest P

Reputation: 87

Junit: How to assert with Get Class Instance

I have the following class BridgeMaps:

public class BridgeMaps {
    private static final BridgeMaps INSTANCE = new BridgeMaps();

    private Map<String, String> docTypeMap;
    private Map<String, String> docBaseMap;
    private Map<String, String> tempFolderIdMap;
    //....

    //constructor for the class to initialize the Maps      
    private BridgeMaps(){
        docTypeMap = new HashMap<String, String>();
        docBaseMap = new HashMap<String, String>();
        docBaseMap = new HashMap<String, String>();
        //....rest of the code

    }


    //Get the class instance 
    //@return BridgeMaps - Returns the BridgeMaps Instance
    public static final BridgeMaps get(){
        return INSTANCE;
    }
}

And I wrote the Junit test case as:

public class BridgeMapsTest {

    private static BridgeMaps bridgeMaps;
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        Constructor<BridgeMaps> b = BridgeMaps.class.getDeclaredConstructor(new Class[0]);
        b.setAccessible(true);
        bridgeMaps = b.newInstance(new Object[0]);
    }

    @Test
    public void testGet() {
        //("Not yet implemented");
    }
}

But I am not sure what to assert:

assertWhat(bridgeMaps.get());

How can I assert the instance of the class in testGet() method?

Any help would be appreciated. Thank you.

Upvotes: 2

Views: 2031

Answers (2)

GhostCat
GhostCat

Reputation: 140457

I suggest to use assertThat.

This assert works with Hamcrest matchers, like notNullValue().

Allowing you to rewrite your assert like this:

assertThat(BridgesMap.get(), notNullValue(BridgeMaps.class))

This code asserts that calling that static get method will returns a non-null value.

In other words: this call will trigger the ctor, and runs all that code behind that. And you can be assured that your singleton is "real", and not null; respectively causes exceptions upon being accessed.

Upvotes: 1

roby
roby

Reputation: 3273

Use assertSame(a,b)

Asserts that two objects refer to the same object.

Also consider just doing assertSame(bridgeMaps.get(), bridgeMaps.get()) instead of that reflective pokery.

Upvotes: 0

Related Questions