junit - 从类中声明的私有静态变量调用的模拟静态方法
问题描述
从类中声明的私有静态变量调用的模拟静态方法。
public class User{
private static int refresh = readConfig();
public static int readConfig(){
// db call
}
}
我尝试使用 powermockito 来模拟 readConfig 方法,但它不起作用。我需要在类加载时模拟 readConfig() 。
PowerMockito.mockStatic(User.class);
PowerMockito.when(User.readConfig()).thenReturn(1);
请让我知道如何模拟 readConfig 方法。
解决方案
虽然您无法模拟与该static
块相关的任何内容,但
您可以PowerMockito
通过使用SuppressStaticInitializationFor
.
请注意,这样做不会执行该readConfig()
方法,并且您的refresh
变量将保留其默认值(在本例中为 0)。
但这对你来说似乎并不重要,因为 - 从你的评论来看 - 你主要试图抑制相关的数据库错误。由于变量是私有的,并且您(必须)模拟所有相关方法,因此在测试期间不太可能使用它。
Reflections
如果您需要将其设置为某个特定值,您将不得不使用。
package test;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;
class User {
protected static int refresh = readConfig();
public static int readConfig(){
return -1;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticTest.class)
@SuppressStaticInitializationFor({"test.User"})
public class StaticTest {
@Test
public void test() throws Exception {
PowerMockito.mockStatic(User.class);
PowerMockito.when(User.readConfig()).thenReturn(42);
Assert.assertEquals(0, User.refresh);
Assert.assertEquals(42, User.readConfig());
}
}
推荐阅读
- java - 将项目收集到括号中(当前组和所有先前组)
- c++ - 变形多态对象
- javascript - 在对象字面量声明中使用自引用时达到 10 次 $digest() 迭代
- javascript - 对象用 ...props 解构所有道具
- java - 为什么自定义阻塞队列在 Java 中不是线程安全的
- mvvmcross - MvvmCross Android: Linking kills SwitchCompat.Checked propety
- excel - 保存前着色数据框
- db2 - SQL0443 error when executing a Select with a Trigger on DB2 for iSeries
- android - 无法为设备建立第二个 Raspberry Pi [WIFI Direct]
- java - 拥有 Hibernate 2 级缓存的 CPU 收益何时超过初始命中