我正在尝试用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
答案 0 :(得分:1)
由于PowerMock尝试更改咬合代码并咬住java.lang
类的代码,因此无法模拟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);