首页 > 解决方案 > 从类中声明的私有静态变量调用的模拟静态方法

问题描述

从类中声明的私有静态变量调用的模拟静态方法。

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 方法。

标签: junitmockitopowermockito

解决方案


虽然您无法模拟与该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());
    }
}

推荐阅读