如何在调用私有方法的Junit4中测试方法

How to test method in Junit4 which calls a private method

我必须测试一个 DAO class,它本身调用一个私有方法。我正在使用 Junit4 和 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());
    }
}

我的测试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);

    }

但是我在 getTableName() 上收到 NPE

根据 OP 中提供的信息,您的测试中似乎正在实例化 UserProfileDAO class,但未设置 tableNameResolver属性。

我建议您在单元测试中使用模拟框架,例如 Mockito。 您可以使用此框架提供模拟实例作为 tableNameResolver 属性的值,然后将其设置在 actual 的实例中,这会导致 NPE在单元测试执行期间。

考虑到您的单元测试实际上是一个集成测试(即涉及多个 classes 的代码流,显然正在测试持久层而不是 [=25= 的简单实现]), 另一种方法可能是在测试单元初始化期间实例化持久层,但这会对单元测试的性能产生负面影响。