首页 > 解决方案 > 尝试使用 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)

请帮助我找到该问题的解决方案。

标签: javajunit4powermock

解决方案


静态方法显然没有被嘲笑。

问题很可能是因为您没有在@PrepareForTest

将其更改为@PrepareForTest({ApproverService.class, ServiceLocator.class})


题外话:

尽管它可以编译,但通过实例引用调用静态方法并不是一个好习惯。因此该行应该是when(ServiceLocator.findService(...)).thenReturn(inboxService)

另一个问题是,您尝试使用单例模式,但方式错误。假设单例会返回一个实例,以便调用者可以调用其实例方法。你findService最好是一个实例方法,并被称为ServiceLocator.getInstance().findService(...). 为了进一步改进,除非你真的需要它是一个单例,否则你应该把它变成一个普通的对象实例并注入需要它的对象(假设你已经在使用 Spring,我认为没有理由制作单例)


推荐阅读