3

可以模拟一个完整的方法吗?或者我是否必须在该方法中模拟每个服务调用?

这是一个(愚蠢的)示例:

class Foo {
   void update() {
      service1.do();
      service2.do();
      //...
   }
}

class Bar extends Foo {

   void save() {
      super.update();
      // doSometing that I want to test.
   }
}

我想测试 Bar.save() ,并且我想模拟 super.update() 中的所有内容,而不必模拟每个服务本身。那可能吗?

4

2 回答 2

2

Your Bar class is-a Foo. Bar has inherited update method from Foo. So you shouldn't mock the method from the class under test. It is much nicer to choose one of this:

  • Consider using composition, then it would be natural way to mock it.
  • Inherit from FooTest. You have tests for Foo, right? You have @Before setup which mock all services there. Reuse it.
于 2013-03-24T12:56:07.180 回答
1

在您的情况下,Bar 似乎扩展了 Foo。

因此,使用框架模拟它更加困难,但您可以在测试中覆盖 update() :

Bar testBar = new Bar() {
@Override
  void update() {
  // do nothing
  }
}

assertSomething(bar.save());

但是...@smas 是对的,需要这样做是一种代码味道,这表明您应该将 is-a 分解为 has-a 关系,然后嘲笑将变得轻而易举:

class Bar {

  private Foo foo;

  public Bar(Foo foo) {
    this.foo = foo;
  }

  void save() {
    foo.update();
  }

}

你的测试:

Bar bar = new Bar(mock(Foo));

assertSomething(bar.update());
于 2013-03-24T12:46:41.177 回答