Powermock和Mockito。在模拟和存根同一个类时,避免对类进行静态初始化

时间:2016-01-27 20:15:24

标签: java junit mockito powermock

假设我有一个名为Util的类,其中包含静态字段:

public class Util {

    public static field = Param.getValue("param1");                 

}

并且Param类看起来像这样:

public class Param {

    public static field = SomeClass.getValue("someValue");

}

我想在Util中模拟和存储Param.getValue(" param1"),但同时我想要抑制Param类的静态初始化。我怎样才能做到这一点?

这是我的第一次尝试,但它无法正常工作

@RunWith(PowerMockRunner.class)
@PrepareForTest({Param.class})
@SuppressStaticInitializationFor("py.com.company.Param")
public class Test {

     @Test
     public void testSomeMethod() {
         PowerMockito.mockStatic(Param.class);
         when(Param.getValue("value1")).thenReturn("someValue1");
     }

}

1 个答案:

答案 0 :(得分:1)

这对我有用。我没有输出,SomeClass#getValue如果没有@SuppressStaticInitializationFor

@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor({"so35047166.Param"})
@PrepareForTest({Param.class})
public class UtilTest {
    @Before
    public void setUp() throws Exception {
        PowerMockito.mockStatic(Param.class);
    }

    @Test
    public void testFoo() throws Exception {
        final Util util = new Util();
        assertEquals("Util#foo", util.foo());
        assertEquals(null, Util.field);
    }
}

使用:

// all in package so35047166;

public class Util {

    public static String field = Param.getValue("param1");

    public String foo() {
        return "Util#foo";
    }
}

public class Param {

    public static String field = SomeClass.getValue("someValue");

    public static String getValue(final String in) {
        System.out.println("Param#getValue");
        return "Param#getValue";
    }
}

public class SomeClass {
    public static String getValue(final String in) {
        System.out.println("SomeClass#getValue");
        return "SomeClass#getValue";
    }
}