当我尝试模拟JTextField
时,会出现此错误。
java.lang.LinkageError: loader constraint violation in interface itable
initialization: when resolving method
"javax.swing.text.JTextComponent$1.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$1, and the class loader
(instance of <bootloader>) for interface
sun/swing/SwingAccessor$JTextComponentAccessor have different Class
objects for the type mponent$1.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.*"})
什么都没用。
根据引用问题的场景,我提出了一个解决方法:问题发生在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());
}
}