Google mock is at least one of several expectations

I use Google Mock to indicate the compatibility level for an external API. There are several ways to do some things in the external API, so I want to point out that at least one (or preferably one) wait is being executed out of many expectations. In pseudo code, this is what I want to do:

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

Can this be done using Google Mock?

+5
source share
1 answer

There are two ways to do this:

  • using custom methods - create a class using the same methods. And then use Invoke() to pass the call to this object
  • using a partial order call - create different expectations in different sequences, as described here

Using custom method

Something like that:

 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 ); } 

using a partial order call

 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(); } 
+1
source

All Articles