public String processName() throws Exception {
String name = dbManager.getName(); // getname
String connection = dbManager.getConnection();
String name2 = dbManager.getName();
Mydata mydata = new Mydata();
String getData = mydata.getGetData();
List<String> list = dbManager.getList();
return getData.toLowerCase();
}
private class Mydata {
String getData = "test";
public String getGetData() {
return getData;
}
public void setGetData(String getData) {
this.getData = getData;
}
}
最佳答案
一般来说,您不应该使用私有(private)
类,并避免为它们编写测试,因为它们应该是外部世界的黑匣子
。
但是,如果您正在使用 JMockit 并想要模拟它,那么您可以通过以下方式使用 JMockit 来实现:
Object ins = Deencapsulation.newInnerInstance("Mydata", outerClass.class, (Object[]) null);
我使用了 null
因为您没有在内部私有(private)类上定义任何构造函数。
如果您有兴趣,这里是文档:
Object mockit.Deencapsulation.newInnerInstance(String innerClassSimpleName, Object outerClassInstance, Object... nonNullArgs)
The same as newInstance(String, Class[], Object), but for instantiating an inner non-accessible class of some other class, and where all other (if any) initialization arguments are known to be non-null.
Parameters:
innerClassSimpleName: the inner class simple name, that is, the part after the "$" character in its full name
outerClassInstance: the outer class instance to which the inner class instance will belong
nonNullArgs: zero or more non-null parameter values for the invocation; if a null value needs to be passed, the Class object for the corresponding parameter type must be passed instead type to which the returned instance should be assignable
Returns: a newly created instance of the specified inner class, initialized > with the given arguments
Throws: IllegalArgumentException - if a null reference was provided for a parameter
关于java - 如何使用jmockit模拟私有(private)类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36031424/