简体   繁体   English

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

[英]How to test method in Junit4 which calls a private method

I have to Test a DAO class, which itself calls a private method.我必须测试一个 DAO 类,它本身调用一个私有方法。 I am using Junit4 and ReflectionTestUtils.我正在使用 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());
    }
}

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()但是我在 getTableName() 上得到了 NPE

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.根据 OP 中提供的信息,似乎UserProfileDAO类正在您的测试中被实例化,而没有设置tableNameResolver属性。

I suggest you use a mocking framework with your unit test, such as Mockito .我建议您在单元测试中使用模拟框架,例如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.您可以使用此框架提供一个模拟实例作为tableNameResolver属性的值,然后将其设置在导致单元测试执行期间 NPE 的实际实例中。

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.考虑到您的单元测试实际上是一个集成测试(即涉及多个类的代码流,显然正在测试持久层而不是 API 的简单实现),另一种方法可能是在测试期间实例化持久层测试单元的初始化,但是这会对单元测试的性能产生负面影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM