0

我试图MBeanServer用 Mockito 模拟,但我的尝试失败了。

@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
4

1 回答 1

2

不可能从java.lang包中模拟静态,因为 PowerMock 试图更改java.lang明显免受修改的类的咬代码和咬代码。

Johan Haleby建议了一些解决方法。您必须创建包装类:

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);
于 2016-09-08T09:53:29.943 回答