Shubham Chopra
Shubham Chopra

Reputation: 1737

How to test method in Junit4 which calls a private method

I have to Test a DAO class, which itself calls a private method. I am using Junit4 and ReflectionTestUtils.

class UserProfileDAO
{
    public void saveOrUpdate(UserProfileEntity userProfile) {

        try {
            userProfile.setDateUpdated(new Date());
            dynamoDB.save(userProfile, getTableName());
        }

        catch (Exception ex) {
            log.error("Error occured while saving data to dynamoDB" + ex);
        }
    }
public String getTableName() {
        return tableNameResolver.getTableName(PropertyEnum.DYNAMODB_OPX_USER_PROFILES_TABLE.getCode());
    }
}

My Test class

@Test
    public void saveOrUpdate() {

            String opxUserID= "50000";
            UserProfileEntity expected = createUserProfileEntity(opxUserID);
            expected.setUserProfileID(12);

            userProfileDynamoDAO.saveOrUpdate(expected);

            // load saved entity
            UserProfileEntity actual = mapper.load(UserProfileEntity.class, opxUserID);
            log.info(actual.toString());

            assertNotNull(actual);
            assertEquals(expected, actual);

    }

But I am getting NPE on getTableName()

Upvotes: 1

Views: 240

Answers (1)

Rann Lifshitz
Rann Lifshitz

Reputation: 4090

Based on the provided info in the OP, it seems like the UserProfileDAO class is being instantiated in your test without setting the tableNameResolver attribute.

I suggest you use a mocking framework with your unit test, such as Mockito. You can use this framework to provide a mock instance as a value of the tableNameResolver attribute, then set it in the instance of actual which causes the NPE during the unit test execution.

Considering the fact that your unit test is actually an integration test (ie. a code flow involving multiple classes and apparently the persistency layer is being tested instead of a simple implementation of an API), another approach could be to instantiated your persistency layer during the initialization of your test unit, however this can negatively effect the performance of your unit tests.

Upvotes: 1

Related Questions