【问题标题】:JUnit Mockito Testing and Spying 2 separate methodsJUnit Mockito 测试和间谍 2 种不同的方法
【发布时间】:2018-05-31 17:55:47
【问题描述】:

我有一个服务类,我想为其编写 junit 测试。这是该服务类:

public class FooService {
  private BarService barService;

  public FooService(BarService barService) {
    this.barService = barService;
  }

  public Foo methodOne(int a) {
    double value = methodTwo();
    //do some other stuff and return Foo
  }

  public double methodTwo() {
    //do stuff
  }
}

这是我的 junit 测试:

public class FooServiceTest {
  @Mock
  BarService barService;
  FooService fooService;

  @Before
  public void init() {
    MockitoAnnotations.initMocks(this);
    fooService = Mockito.spy(new FooService(barService));
    doReturn(1.0).when(fooService).methodTwo();
    doCallRealMethod().when(fooService).methodOne(1);
  }

  @Test
  public void test() {
    fooService.methodOne(1);
    assertThat(.....)
  }
}

我的问题是,当我运行测试时,它实际上从未调用过methodOne。它只是跳过FooService 中的所有内容并直接转到asserThat(...) 行。我觉得这与监视 fooService 对象有关。

如何为这个 FooService 编写一个 junit 测试,在其中我真正调用 methodOne 但我模拟了 methodTwo 的返回?

【问题讨论】:

  • 我试过这段代码,调用了真正的methodOne。你能在methodOne(int a) 中添加System.out.println("methodOne called"); 并检查它是否打印出来吗?
  • 是否有必要只模拟methodTwo?必须公开 methodTwo() 还是仅出于测试目的更改它?

标签: java junit mocking mockito stub


【解决方案1】:

我猜你让它有点复杂。你对spy 的看法是对的:

public class FooService {

    BarService barService;

    public FooService(BarService barService) {
        this.barService = barService;
    }

    public String methodOne(int a) {
        double value = methodTwo();
        return "Hello from method 1 - " + value;
    }

    public double methodTwo() {
        return 1;
    }
}


public class MyTest {

    private BarService barService = Mockito.mock(BarService.class);
    private FooService fooService = Mockito.spy(new FooService(barService));

    @Test
    void test() {
       doReturn(7.0).when(fooService).methodTwo();
       String result = fooService.methodOne(1);
       assertThat(result).isEqualTo("Hello from method 1 - 7.0");
    }

}

如果您使用间谍,所有未模拟的方法都将是“真实”的。所以不用说doCallRealMethod()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多