java - 如何使用jmockit模拟私有(private)类?

标签 java junit junit4 jmockit

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/

相关文章:

java - Mac OS X - 最后修改日期为 0

java - 复制任务未将复制的文件放入其TaskOutputs中-为什么?

java - 网 bean 7 : How to unwrap long lines of code and editor context-menu "Format"

java - GraniteDS 与 Parsley 框架

java - Selenium 测试运行不会保存 cookie?

java - 如何在单元测试中模拟/ stub Java 容器?

java - 测试具有外部依赖的类的最佳方法是什么

java - 异常堆栈上的 Mule JUnit 测试

java - 当 JUnit 找不到测试类时,如何从 jar 中运行 JUnit 测试

java.lang.AssertionError : Expectation failure on Verify: jUnit4 TestCase