java.lang.LinkageError: loader constraint violation in interface itable initialization:

java.lang.LinkageError: loader constraint violation in interface itable initialization:

当我尝试模拟 JTextField 时出现此错误。

java.lang.LinkageError: loader constraint violation in interface itable
    initialization: when resolving method
    "javax.swing.text.JTextComponent.dropLocationForPoint(
    Ljavax/swing/text/JTextComponent;Ljava/awt/Point;)Ljavax/
    swing/TransferHandler$DropLocation;" the class loader (instance of
    org/powermock/core/classloader/MockClassLoader) of the current
    class, javax/swing/text/JTextComponent, and the class loader
    (instance of <bootloader>) for interface
    sun/swing/SwingAccessor$JTextComponentAccessor have different Class
    objects for the type mponent.dropLocationForPoint(Ljavax/swing/text/
    JTextComponent;Ljava/awt/Point;)Ljavax/swing/TransferHandler$
    DropLocation; used in the signature
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:191)
at javassist.runtime.Desc.getClassObject(Desc.java:43)

我试过用这个:

@PowerMockIgnore( {"javax.management.*","javax.security.*","javax.ws.*"}) 

没有任何效果。

基于 cited issue 的场景,我提出了一个解决方法:问题出现在 javax.swing.text.JTextComponent 的静态初始化程序中,因此我们可能 抑制 该代码使用 @SuppressStaticInitializationFor("javax.swing.text.JTextComponent").

这是一个有效的测试用例(使用 Powermock 1.6.4):

import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;

import javax.swing.JOptionPane;
import javax.swing.JTextArea;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(JOptionPane.class)
@SuppressStaticInitializationFor("javax.swing.text.JTextComponent")
public class PowerMockIssue {
    @Test
    public void powermockTest() {
        final JTextArea textArea = mock(JTextArea.class);
        when(textArea.getText()).thenReturn("test");
        Assert.assertEquals("test", textArea.getText());
    }
}