java - 从本地内部类模拟访问外部对象

标签 java unit-testing junit mockito

我在其中一个方法中有一个带有局部内部类的类:

public class Outer {
    String hello = "hello";

    public void myMethod() {

        class Inner {
            public void myInnerMethod() {
                System.out.println(hello);         
            }
        }

        [...really slow routine...]

        (new Inner()).myInnerMethod();
    }
}

我想测试 myInnerMethod()。因此,我使用反射实例化本地内部类,并对其调用 myInnerMethod()

public void test() {
    Object inner = Class.forName("Outer$Inner").newInstance();
    inner.getClass().getDeclaredMethod("myInnerMethod").invoke(inner); // hello will be null
}

但是当 myInnerMethod() 访问 hello 时,它在 Outer 类的范围内,它是 null

有没有办法模拟或以其他方式向 myInnerMethod() 提供 hello?

我知道我可以通过提取内部类或只测试 Outer 的公共(public)方法来重构我的代码。但是还有办法吗?

最佳答案

在能够验证内部行为之前,您需要进行一些小的重构:

1) 创建一个包含从 myInnerMEthod 中调用的代码的包级方法:

public class Outer {
    String hello = "hello";

    public void myMethod() {

        class Inner {
            public void myInnerMethod() {
                Outer.this.printHello(hello);    // !!! change here     
            }
        }

        [...really slow routine...]

        (new Inner()).myInnerMethod();
    }

    void printHello(String hello){/* */}   // !! add this
}

2) 监视 Outer 类并验证 printHello 是否已使用 hello 实例变量调用:

public void test() {
    // Arrange
    Outer outerSpy = spy(new Outer());
    doNothing().when(outerSpy).printHello(anyString()); // optional

    // Act
    outer.myMethod();

    // Assert
    verify(outerSpy).printHello("hello");
}

关于java - 从本地内部类模拟访问外部对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55628238/

相关文章:

java - Visual Studio 浮点/单一操作输出错误

java - 在 Java 中从 Receiver 获取 midi 消息

asp.net-mvc - 单元测试 Razor View

javascript - 断言失败,因为它不等待 promise 解决

java - 让 DbUnit 与 Hibernate 事务一起工作

testing - 在相同的浏览器 session 中使用 Selenium

java - 匿名内部类——集合排序

java - 将 JList 值从 JFrame 传递到 JDialog

javascript - 在 Jest 中模拟类模块

grails - 如何在 junit 测试 groovy 和 grails 中模拟 RequestContextHolder