简体   繁体   English

验证模拟对象的方法

[英]Verify a mocked object's method

Say I have a class like this: 说我有一个这样的班级:

public class Foo {
    private Bar bar;
    public Foo(Bar bar) {
        this.bar = bar;
    }

    public void someMethod() {
        bar.someOtherMethod();
    }
}

How would I verify that bar.someOtherMethod() is called once when someMethod() is called? 调用someMethod()时,如何验证一次bar.someOtherMethod()被调用? In my test, I am passing in a mocked Bar class into the constructor. 在测试中,我将模拟的Bar类传递给构造函数。

My test looks something like this: 我的测试看起来像这样:

private Bar bar;
private Foo foo;

@Before
public void setUp() throws Exception {
    bar = mock(Bar.class);
    foo = new Foo(bar);
}

@Test
public void testSomeMethod() {
    foo.someMethod();
    verify(Bar).someOtherMethod();
}

与Mockito-

verify(mockBar, times(1)).someOtherMethod();

Since you're passing in the instance of Bar , it's relatively straightforward: 由于您传递的是Bar实例,因此相对简单:

  • Interact with the mock (ie you have to expect that the mock does something (or nothing, in this case) 与模拟进行交互(即,您必须期望模拟能够执行某些操作(在这种情况下,什么都不做)
  • Expect that it was interacted with exactly once 期望它曾经与之交互过一次

With that, you can employ something like this in your test: 这样,您就可以在测试中采用类似的方法:

doNothing().when(mockBar).someOtherMethod();
foo.someMethod();
verify(mockBar).someOtherMethod();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM