java - 尝试使用 ApplicationContext 时的 PowerMockito 空指针
问题描述
我有一个类名 ServiceLocator
public class ServiceLocator implements ApplicationContextAware {
private transient ApplicationContext _applicationContext;
private static ServiceLocator _instance = new ServiceLocator();
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
_instance._applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return _instance._applicationContext;
}
public static Object findService(String serviceName) {
return _instance._applicationContext.getBean(serviceName);
}
}
我正在尝试使用该类将 Service 查找到 Approver 类方法中
public class ApproverService extends AbstractDataService implements IApproverService {
public void updateCompletedInboxStatus(String status) {
IInboxService inboxService = (IInboxService)ServiceLocator.findService("inboxService");
InboxItem inboxItem = inboxService.getInboxItem("test");
inboxItem.setWorkItemStatus(status);
inboxService.saveInboxItem(inboxItem);
}
}
使用该代码,我正在尝试使用 PowerMockRunner 编写 Junit
@RunWith(PowerMockRunner.class)
@PrepareForTest({ApproverService.class})
public class ApproverServiceTest {
@InjectMocks
ApproverService approverService;
@Mock
IInboxService inboxService;
@Mock
ServiceLocator serviceLocator;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void updateCompletedInboxStatus() {
RequestAccessHeader reqHdr = new RequestAccessHeader();
reqHdr.setRequestStatus(AccessConstants.REQ_STATUS_HOLD_INT);
String status = "test";
PowerMockito.mockStatic(ServiceLocator.class);
when(serviceLocator.findService("inboxService")).thenReturn(inboxService);
approverService.updateCompletedInboxStatus(status);
}
}
但我得到空指针
java.lang.NullPointerException at com.alnt.fabric.common.ServiceLocator.findService(ServiceLocator.java:25) at com.alnt.access.approver.service.ApproverServiceTest.updateCompletedInboxStatus(ApproverServiceTest.java:80)
请帮助我找到该问题的解决方案。
解决方案
静态方法显然没有被嘲笑。
问题很可能是因为您没有在@PrepareForTest
将其更改为@PrepareForTest({ApproverService.class, ServiceLocator.class})
题外话:
尽管它可以编译,但通过实例引用调用静态方法并不是一个好习惯。因此该行应该是when(ServiceLocator.findService(...)).thenReturn(inboxService)
。
另一个问题是,您尝试使用单例模式,但方式错误。假设单例会返回一个实例,以便调用者可以调用其实例方法。你findService
最好是一个实例方法,并被称为ServiceLocator.getInstance().findService(...)
. 为了进一步改进,除非你真的需要它是一个单例,否则你应该把它变成一个普通的对象实例并注入需要它的对象(假设你已经在使用 Spring,我认为没有理由制作单例)
推荐阅读
- c# - http请求不使用json格式
- python - 向具有 CSRF 保护的 Ruby on Rails 应用程序发出 POST 请求时出现 404 错误
- dataframe - 如何使用 PySpark 在数据框中过滤字符串类型的嵌套列
- python - 无法使用 beautifulsoup 抓取 div 文本
- java - 按下回车键后如何限制扫描仪对象接受任何内容
- javascript - 如何计算两个日期选择器之间的总天数并将结果显示在另一个文本字段中?
- firebase - 此项目设置为在 Datastore 模式下使用 Cloud Firestore。此模式只能从谷歌云平台访问
- javascript - 如何根据屏幕大小使用javascript调整菜单的填充?
- php - 图片必须是图片
- blazor - Blazor 组件生命周期方法 OnParametersSet 行为