Mockito - 如何验证模拟从未被调用过

And*_*s_D 49 java junit mockito

我正在寻找一种方法来验证Mockito,在测试期间没有与给定模拟器的任何交互.对于具有验证模式的给定方法,很容易实现never(),但我还没有找到完整模拟的解决方案.

我实际想要实现的目标:在测试中验证,没有任何内容打印到控制台.jUnit的一般想法是这样的:

private PrintStream systemOut;

@Before
public void setUp() {
    // spy on System.out
    systemOut = spy(System.out);
}

@After
public void tearDown() {
    verify(systemOut, never());  // <-- that doesn't work, just shows the intention
}
Run Code Online (Sandbox Code Playgroud)

A PrintStream有很多方法,我真的不想用每个单独的验证验证每个方法 - 对于System.err...来说也是如此

所以我希望,如果有一个简单的解决方案,我可以,鉴于我有一个很好的测试覆盖率,迫使软件工程师(和我自己)删除他们的(我的)调试代码,System.out.println("Breakpoint#1");或者e.printStacktrace();在提交更改之前或之前.

gon*_*ard 65

用这个 :

import static org.mockito.Mockito.verifyZeroInteractions;

// ...

private PrintStream backup = System.out;

@Before
public void setUp() {
    System.setOut(mock(PrintStream.class));
}

@After
public void tearDown() {
    verifyZeroInteractions(System.out);
    System.setOut(backup);
}
Run Code Online (Sandbox Code Playgroud)

  • verifyZeroInteractions 现已被弃用,取而代之的是“org.mockito.Mockito#verifyNoInteractions” (13认同)

Don*_*oby 11

verifyZeroInteractions(systemOut);
Run Code Online (Sandbox Code Playgroud)

如评论中所述,这不适用于间谍.

对于大致相当但更完整的答案,请参阅gontard对此问题的回答.


McD*_*ell 5

您可以尝试稍微不同的方法:

private PrintStream stdout;

@Before public void before() {
    stdout = System.out;
    OutputStream out = new OutputStream() {
        @Override public void write(int arg0) throws IOException {
            throw new RuntimeException("Not allowed");
        }
    };
    System.setOut(new PrintStream(out));
}

@After public void after() {
    System.setOut(stdout);
}
Run Code Online (Sandbox Code Playgroud)

如果您愿意,您可以切换模拟的匿名类型并按照 Don Roby 的建议进行验证。


Rob*_*ain 5

由于原始正确答案verifyZeroInteractions已被弃用,请verifyNoInteractions改用:

import org.junit.jupiter.api.Test;

import static org.mockito.Mockito.*;

public class SOExample {

    @Test
    public void test() {
        Object mock = mock(Object.class);
        verifyNoInteractions(mock);
    }
}
Run Code Online (Sandbox Code Playgroud)