PowerMock:如何间谍的System.out.println?

问题描述 投票:1回答:1

比方说,我有下面的类:

class MyClass { 
    public MyClass(){
    }
    public void hello() {
       System.out.println("hello");
    }
}

我想测试“你好”方法:

@Test
public void testHello() {
    MyClass mc = new MyClass();
    mc.hello();
}

现在,我想窥探的System.out.println,并确保这种方法被称为用“你好”作为参数。我该怎么做?

junit mockito powermock
1个回答
2
投票

System.out实际上是PrintStream的一个实例,所以我的做法是创建这个类,并直接输出,使用System.setOut方法的模拟:

PrintStream outMock = Mockito.mock(PrintStream.class);
System.setOut(outMock);
System.out.println("Hello");
Mockito.verify(outMock).println("Hello");

记得在测试后恢复以前PrintStream情况下,最好在finally条款。

© www.soinside.com 2019 - 2024. All rights reserved.