when i use PowerMockito to test a method,the code is
public class RedisLockUtil {
private static final StringRedisTemplate STRING_REDIS_TEMPLATE = SpringContextUtil.getBean(StringRedisTemplate.class);
public static boolean getLock(String lockId, long second) {
log.info("lock by key:[{}],last :[{}] s", lockId, second);
Boolean success = STRING_REDIS_TEMPLATE.opsForValue().setIfAbsent(lockId, "lock",
second, TimeUnit.SECONDS);
return success != null && success;
}
}
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({RedisLockUtil.class})
public class Mock {
@Before
public void setUp() {
PowerMockito.mockStatic(RedisLockUtil.class);
MockitoAnnotations.initMocks(this);
}
@Test
public void test(){
RedisLockUtil.getLock("test",1L);
}
}
i need to test the createUserLockKey method,but the STRING_REDIS_TEMPLATE need to be initialized。but i dont konw how to set ApplicationContext,so the method-getApplicationContext() will return null,and when RedisLockUtil invoke the getBean,it will throw NullPointException.
so how can i make the ApplicationContext not null?