我有以下情况:
- A 类,在静态 block 中进行一些初始化。
- A 类 B 需要第一个类 A。
A 类不在我的控制之下,它来自一个库,我无法替换该库或 A 类。
当我想为 B 类编写单元测试并尝试模拟 A 类时,执行 A 类的静态 block ,我得到:
java.lang.ExceptionInInitializerError
at sun.reflect.GeneratedSerializationConstructorAccessor1.newInstance(Unknown Source)
...
Caused by: org.eclipse.core.runtime.AssertionFailedException: assertion failed: The application has not been initialized.
at org.eclipse.core.runtime.Assert.isTrue(Assert.java:110)
at org.eclipse.core.internal.runtime.InternalPlatform.assertInitialized(InternalPlatform.java:139)
at org.eclipse.core.internal.runtime.InternalPlatform.getAdapterManager(InternalPlatform.java:160)
at org.eclipse.core.runtime.Platform.getAdapterManager(Platform.java:595)
at test.A.<clinit>(A.java:12)
... 43 more
以下是 A 类、B 类和测试:
A.java
package test;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.Platform;
public class A {
static {
IAdapterManager adapterManager = Platform.getAdapterManager();
}
public A() {
}
public void doSomething() {
//
}
}
B.java
package test;
public class B {
private A a;
public B(A a) {
this.a = a;
}
public B() {
}
public void someMethod() {
a.doSomething();
}
public void setA(A a) {
this.a = a;
}
}
TestB.java
package test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
public class TestB {
private B b;
private A a;
@Before
public void setUp() throws Exception {
a = Mockito.mock(A.class);
b = new B(a);
}
@Test
public void testSomeMethod() throws Exception {
//
}
@After
public void tearDown() throws Exception {
//
}
}
那么,问题是,我应该在单元测试中做什么来在“Mockito.mock(A.class);”之前初始化 eclipse 平台?
问题在于,当调用“Platform.getAdapterManager()”时,先调用“InternalPlatform.getDefault().getAdapterManager()”,然后再调用“assertInitialized()”,这会抛出“java.lang.ExceptionInInitializerError” “与
Caused by: org.eclipse.core.runtime.AssertionFailedException: assertion failed: The application has not been initialized.
最佳答案
你可以尝试PowerMock它支持删除静态初始值设定项。请参阅here举个例子。
总之,您可以使用 @RunWith(PowerMockRunner.class)
和 @SuppressStaticInitializationFor("org.mycompany.ClassWithStaticInitializer")
注释您的测试类。
关于java - 启动eclipse平台进行junit测试时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26724980/