when I try to mock a static method likes SpringUtils.getBean("BeanName") with Mockito 3.7.7, , and I got a NullPointerException of applicationContext, and the getBean("BeanName") method seems still been executed, Here is my code as fellow:
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
// NullPointerException here
return (T) applicationContext.getBean(name);
}
}
And this is where I use SpringUtils:
public class Aaa{
public Integer getSpringBean(){
RedisTemplate<String,Object> redisTemplate = SpringUtils.getBean("abc");
System.out.println(1234);
return 5;
}
}
The test code as fellow:
@Test
public void test(){
Aaa a = new Aaa();
try (MockedStatic<SpringUtils> theMock1 = Mockito.mockStatic(SpringUtils.class)) {
theMock1.when(()->SpringUtils.getBean(Mockito.anyString())).thenReturn(Mockito.mock(RedisTemplate.class));
}
Integer x = a.getSpringBean();
System.out.println(x);
}
then I got a NullPointerException:
java.lang.NullPointerException
at com.labs.common.idgenerator.utils.SpringUtils.getBean(SpringUtils.java:42)
at com.labs.common.idgenerator.config.Aaa.getSpringBean(Aaa.java:24)
so, how to mock SpringUtils.getBean("beanName") with mockito correctly?
Best Regards!
question from:
https://stackoverflow.com/questions/65951409/how-to-mock-springutils-getbeanbeanname-by-mockito-mockstaticspringutils-cl 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…