在静态方法Junit中获取空指针

时间:2017-07-11 07:07:30

标签: java spring unit-testing junit4

我有以下服务

public UserActivityLog save(UserActivityLog userActivityLog){
    LOGGER.debug("User activity save called.");
    userActivityLog.setCreatedByUser(User.getUser().getUserId());
    userActivityLog.setCreationTime(new Date());
    return activityLogRepository.save(userActivityLog); 
}

我写了以下Junit来测试这个但是得到了用户

的空指针
@RunWith(MockitoJUnitRunner.class)
public class ActivityHistoryServiceTest {

@InjectMocks
private ActivityHistoryService activityHistoryService;

@Mock
private ActivityLogRepository activityLogRepository;

@Test
public void testSave() {
    UserActivityLog userActivityLog = new UserActivityLog();
    /* Called some setter methods to set value here*/
    UserProfile profile = new UserProfile();
    Mockito.when(User.getUser()).thenReturn(profile);
    Assert.assertNotNull(activityLogRepository.save(userActivityLog));  
}

}

用户类就像

public class User {
private User(){}

public static UserProfile getUser(){
    /*some logic*/

    return userProfile;
}

}

请为此提供帮助。提前谢谢。

2 个答案:

答案 0 :(得分:0)

静态方法在有用时很有用。使用它们作为单身人士的替代不是一个很好的做法。而不是您拥有的代码可能如下所示:

public class MyClass {

    private final Logger logger;
    private final UserProvider userProvider;
    private final DateProvider dateProvider;

    /** Constructor that sets all attributes */
    public MyClass(...) {...}

    public UserActivityLog save(UserActivityLog userActivityLog){
        LOGGER.debug("User activity save called.");
        userActivityLog.setCreatedByUser(userProvider.get().getUserId());
        userActivityLog.setCreationTime(dateProvider.get());
        return activityLogRepository.save(userActivityLog); 
    }
}

Provider类非常简单。他们只有一个get()方法,返回所需类型的实例:

public class DateProvider {
    public Date get() {
        return new Date();
    }
}
public class UserProvider {
    public User get() {
        ...
    }
}

使用此设置,您可以轻松模拟依赖项

答案 1 :(得分:0)

您需要PowerMock来模拟静态方法。 参考: https://blog.codecentric.de/en/2016/03/junit-testing-using-mockito-powermock/