使用power mockito的模拟静态方法



我有一个类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;
}

我正试图为这个方法编写一个测试用例。系统设置是另一类和

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

`给出另一个类的实例,并在path中包含类似\var\log文件的路径文件。

我正在尝试使用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方法。任何关于如何调用静态方法的建议都将受到的赞赏

您不应该模拟被测对象。您模拟测试对象的依赖关系,这些依赖关系是完成测试所必需的。

该代码还与诸如文件读取器和缓冲区读取器之类的实现问题紧密耦合。

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

在这种情况下,您只需要模拟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
}
}

参考使用PowerMock与Mockito:模拟静态方法

最新更新