java—我在junit测试中遇到了一个异常,有没有控制它的方法

vybvopom  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(375)
public class Foo {
  private BarFactory barFactory;

  public Foo(BarFactory factory) {
    this.barFactory = factory;
  }

  public void foo() {
    service();
    Bar bar = this.barFactory.createBar();
    bar.someMethod();
  }

  public void service(){
    //Performs some service 
  }

}

Foo foo = new Foo(myFactory);

@Test
public void testDoFoo() {
  Bar bar = mock(Bar.class);

  foo.foo();//service() method throws an exception

  verify(bar, times(1)).someMethod();
}

我必须验证bar.somemethod()是否运行过一次,但service()方法在ut中执行foo()方法时引发错误。有没有办法只测试bar.somemethod()而忽略ut中的服务方法。我不需要测试service()方法。

gj3fmq9x

gj3fmq9x1#

Mockito 有一个 doNothing 方法将void方法设置为不执行任何操作。
见下例:

@RunWith(MockitoJUnitRunner.class)
public class FooTest {

    @Spy
    @InjectMocks
    private Foo foo;

    @Mock
    private BarFactory myFactory;

    @Mock
    private Bar bar;

    @Test
    public void testDoFoo() {
        doReturn(bar).when(myFactory).createBar();
        doNothing().when(foo).service();

        foo.foo();

        verify(bar, times(1)).someMethod();
    }

}

相关问题