gpt4 book ai didi

java - 使用 powermockito 模拟静态方法

转载 作者:行者123 更新时间:2023-11-29 04:13:44 25 4
gpt4 key购买 nike

我有一个类 Engine.class

静态函数

public static  HashMap<String, String> loadLanguageCodeFile(HashMap<String,String> hash_map) {
SystemSettings settings;
FileReader fr = null;
BufferedReader br = null;
try {
settings = SystemSettings.GetInstance();
String path = settings.getLangCodePath();
fr = new FileReader(path + FILENAME);
br = new BufferedReader(fr);
String Line;
while ((Line = br.readLine())!= null) {
String[] lang_codes = Line.split("\\s+");
hash_map.put(lang_codes[0], lang_codes[1]);
}
} catch (IOException e) {
log.error("MicrosoftEngine: Unable to load file.", e);
} catch (WorldlingoException e){
log.error("MicrosoftEngine:", e);
}
finally {
try {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
} catch ( IOException e) {
log.error("MicrosoftEngine : An error occured while closing a resource.", e);
}
}
return hash_map;
}

我正在尝试为此方法编写一个测试用例。 Systemsetting是另一个类和

settings = SystemSettings.GetInstance();
String path = settings.getLangCodePath();

` 给出另一个类的实例并包含路径文件,如\var\log file in path 。

我正在尝试使用 mockito 编写测试用例。由于它是一个静态类,所以我使用了 powermockito。

@RunWith(PowerMockRunner.class)
@PrepareForTest({HttpClientBuilder.class,Engine.class, SystemSettings.class})

public class EngineTest extends TestCase {

public void testLoadLanguageCodeFile() throws Exception {
PowerMockito.mockStatic(Engine.class);
PowerMockito.mockStatic(SystemSettings.class);
MicrosoftEngine MSmock = Mockito.mock(Engine.class);
SystemSettings SystemSettingsMock = Mockito.mock(SystemSettings.class);
Mockito.when(SystemSettingsMock.GetInstance()).thenReturn(SystemSettingsMock);
HashMap<String, String> hash_map = new HashMap<String, String>();
MSmock.loadLanguageCodeFile(hash_map);
}

我无法调用上面的 loadLanguageCodeFile 方法。任何有关如何调用静态方法的建议都将不胜感激

最佳答案

你不应该 mock 被测对象。您模拟被测对象的依赖项,这些依赖项是完成测试所需的。

该代码还与文件读取器和缓冲区读取器等实现问题紧密耦合。

但是,如评论中所述,您希望在模拟设置提供的路径上测试文件的实际读取。

在那种情况下,您只需要模拟 SystemSettings 并且应该调用被测的实际成员

RunWith(PowerMockRunner.class)
@PrepareForTest({SystemSettings.class})
public class EngineTest extends TestCase {
public void testLoadLanguageCodeFile() throws Exception {
//Arrange
String path = "Path to test file to be read";
PowerMockito.mockStatic(SystemSettings.class);
//instance mock
SystemSettings settings = Mockito.mock(SystemSettings.class);
Mockito.when(settings.getLangCodePath()).thenReturn(path);
//mock static call
Mockito.when(SystemSettings.GetInstance()).thenReturn(settings);
HashMap<String, String> hash_map = new HashMap<String, String>();

//Act
HashMap<String, String> actual = Engine.loadLanguageCodeFile(hash_map);

//Assert
//perform assertion
}
}

引用 Using PowerMock with Mockito: Mocking Static Metho

关于java - 使用 powermockito 模拟静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53599483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com