Sha*_*han 5 java junit mockito powermockito powermockrunner
我有一个类,其中有一个我想测试的方法,但它调用同一类中的私有方法来获取 Map 值。我想模拟私有方法返回给我想要测试的方法的内容。
import java.util.*;
public class ClassOne {
public List<String> getList(String exampleString) {
List<String> exampleList = null;
Map<String, String> exampleMap = getMap();
String exampleValue = exampleMap.get(exampleString);
// Does some stuff
exampleList = Arrays.asList(exampleValue.split(","));
return exampleList;
}
private Map<String, String> getMap(){
Map<String, String> exampleMap = new HashMap<>();
exampleMap.put("pre-defined String", "pre-defined String");
return exampleMap;
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知,我似乎想使用 PowerMock,但我似乎无法弄清楚。
一种在 getList 方法调用私有方法 getMap() 时模拟其返回的方法。
您应该能够使用 powermock 来模拟它
\n“使用 PowerMock 模拟私有方法 | Baeldung” https://www.baeldung.com/powermock-private-method
\n\n\n4.1. 无参数但有返回值的方法
\n作为一个简单的示例,let\xe2\x80\x99s 模拟不带参数的私有方法的行为,并强制它返回所需的值:
\nRun Code Online (Sandbox Code Playgroud)\nLuckyNumberGenerator mock = spy(new LuckyNumberGenerator());\n\nwhen(mock, "getDefaultLuckyNumber").thenReturn(300);\n在本例中,我们模拟私有方法 getDefaultLuckyNumber 并使其返回值 300。
\n
| 归档时间: |
|
| 查看次数: |
16440 次 |
| 最近记录: |