3

Problem

Could not initialize class ...

  • ...javax.xml.transform.FactoryFinder (in our case).
  • In the article, where we found the solution, it was the class SessionFactory.

Class Under Test

We wanted to write a test for a utils class with static members. We got the error when trying to create a Mock of a class, which contained a new statement as an initialization of a static field.

public class ClassUnderTest{
    private static JavaType javaType =  new JavaType();
    // ...
}

Test Class

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassUnderTest.class)
public class TestForClassUnderTest {

    @Test
    public void testCase() {

        PowerMockito.mockStatic(ClassUnderTest.class);
Mue
  • 191
  • 2
  • 8

1 Answers1

3

Solution

The solution was adding another class level annotation to the test class:

@SuppressStaticInitializationFor("com.example.package.util.ClassUnderTest")

Note, that you have to give the package path and no .class at the end. Unlike @PrepareFor.

Thanks to this article: http://www.gitshah.com/2010/06/how-to-suppress-static-initializers.html

Test Class with Solution

//...
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassUnderTest.class)
@SuppressStaticInitializationFor("com.example.package.util.ClassUnderTest") // <-- this is it :)
public class TestForClassUnderTest {

  @Test
  public void testCase() {
    PowerMockito.mockStatic(ClassUnderTest.class);
    //...
  }
}

Mue
  • 191
  • 2
  • 8