mockStatic:使用 PowerMock 模拟 java.lang

mockStatic: mock java.lang with PowerMock

我正在尝试使用 Mockito 模拟 MBeanServer,但我的尝试失败了。

@Test
public void testGetAllCacheProperties() {
    mockStatic(ManagementFactory.class);
    MBeanServer server = MBeanServerFactory.newMBeanServer();
    ObjectInstance inst = server.registerMBean(new MyBeanService(), ObjectName.getInstance(SERVICE_NAME));  
    given(ManagementFactory.getPlatformMBeanServer()).willReturn(server);
}

我想将我的模拟注入通常在 jBoss AS 7:

上运行的方法
@GET
public Response getAllProperties() {
    MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); 

但它失败了,异常:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
JmxMBeanServer cannot be returned by getPlatformMBeanServer()
getPlatformMBeanServer() should return MBeanServer 

更新

当我尝试时

 PowerMockito.doReturn(server).when(ManagementFactory.class, "getPlatformMBeanServer");

我得到异常:

java.lang.LinkageError: loader constraint violation: when resolving method "java.lang.management.ManagementFactory.getPlatformMBeanServer()Ljavax/management/MBeanServer;" the class loader (instance of org/powermock/core/classloader/MockClassLoader) of the current class, my_package_for_test_class.TestClass, and the class loader (instance of <bootloader>) for the method's defining class, java/lang/management/ManagementFactory, have different Class objects for the type javax/management/MBeanServer used in the signature

无法从 java.lang 包中模拟静态,因为 PowerMock 试图更改 java.lang classes 的 bite 代码和 bite 代码 显然受到修改保护。

Johan Haleby 建议有变通办法。 您必须创建包装器 class:

public class JmxUtils {

    public static MBeanServer getPlatformMbeanServer() {
        return ManagementFactory.getPlatformMBeanServer();
    }
}

然后测试将如下所示

@RunWith(PowerMockRunner.class)
@PrepareForTest(JmxUtils.class)
public class CacheControllerTest {
    //.. preconditions
    given(JmxUtils.getPlatformMbeanServer()).willReturn(server);