谷歌嘲笑——至少是众多期望中的一个

Google mock - at least one of multiple expectations

本文关键字:期望中 一个 谷歌      更新时间:2023-10-16

我使用Google Mock为外部API指定一个兼容层。在外部API中,执行某些操作有多种方法,因此我希望指定至少满足一组期望中的一个(或者最好是一个)期望。在伪代码中,我想这样做:

Expectation e1 = EXPECT_CALL(API, doFoo(...));
Expectation e2 = EXPECT_CALL(API, doFooAndBar(...));
EXPECT_ONE_OF(e1, e2);
wrapper.foo(...);

这是可能做到使用谷歌模拟?

有两种方法:

  1. 带有自定义方法的执行器-创建一个类,使用相同的方法。然后使用Invoke()将调用传递给该对象
  2. 使用偏序调用-在不同的序列中创建不同的期望,如这里所述

带有自定义方法executor

像这样:

struct MethodsTracker {
   void doFoo( int ) {
     ++ n;
   }
   void doFooAndBar( int, int ) {
     ++ n;
   }
   int n;
};
TEST_F( MyTest, CheckItInvokesAtLeastOne ) {
  MethodsTracker tracker;
  Api obj( mock );
  EXPECT_CALL( mock, doFoo(_) ).Times( AnyNumber() ).WillByDefault( Invoke( &tracker, &MethodsTracker::doFoo ) );
  EXPECT_CALL( mock, doFooAndBar(_,_) ).Times( AnyNumber() ).WillByDefault( Invoke( &tracker, &MethodsTracker::doFooAndBar ) );
  obj.executeCall();
  // at least one
  EXPECT_GE( tracker.n, 1 );
}

使用偏序调用

TEST_F( MyTest, CheckItInvokesAtLeastOne ) {
      MethodsTracker tracker;
      Api obj( mock );
      Sequence s1, s2, s3, s4;
      EXPECT_CALL(mock, doFoo(_)).InSequence(s1).Times(AtLeast(1));
      EXPECT_CALL(mock, doFooAndBar(_,_)).InSequence(s1).Times(AtLeast(0));
      EXPECT_CALL(mock, doFoo(_)).InSequence(s2).Times(AtLeast(0));
      EXPECT_CALL(mock, doFooAndBar(_,_)).InSequence(s2).Times(AtLeast(1));
      EXPECT_CALL(mock, doFooAndBar(_,_)).InSequence(s3).Times(AtLeast(0));
      EXPECT_CALL(mock, doFoo(_)).InSequence(s3).Times(AtLeast(1));
      EXPECT_CALL(mock, doFooAndBar(_,_)).InSequence(s4).Times(AtLeast(1));
      EXPECT_CALL(mock, doFoo(_)).InSequence(s4).Times(AtLeast(0));
      obj.executeCall();
}