DEV Community

Cover image for Functions calling order in unit tests in C++
pikoTutorial
pikoTutorial

Posted on • Originally published at pikotutorial.com

Functions calling order in unit tests in C++

Welcome to the next pikoTutorial !

To ensure a certain order of function calls, GTest provides 2 ways to do that:

  • InSequence object
  • Sequence object

## InSequence object

The simplest way to expect specific function call order is to create a InSequence object in dedicated scope:

#include <gmock/gmock.h>
#include <gtest/gtest.h>

using namespace ::testing;

struct SomeInterface
{
    virtual ~SomeInterface() = default;

    virtual void FirstMethod() = 0;
    virtual void SecondMethod() = 0;
    virtual void ThirdMethod() = 0;
    virtual void FourthMethod() = 0;
};

struct SomeMock : public SomeInterface
{
    MOCK_METHOD(void, FirstMethod, (), (override));
    MOCK_METHOD(void, SecondMethod, (), (override));
    MOCK_METHOD(void, ThirdMethod, (), (override));
    MOCK_METHOD(void, FourthMethod, (), (override));
};

void SomeFunctionToTest(SomeInterface &obj)
{
    obj.FirstMethod();
    obj.SecondMethod();
    obj.ThirdMethod();
    obj.FourthMethod();
}

TEST(TestSomeFunction, CallingOrderIsCorrect)
{
    SomeMock obj;

    {
        // in this scope the call order matters...
        InSequence seq;

        EXPECT_CALL(obj, FirstMethod);
        EXPECT_CALL(obj, SecondMethod);
    }

    // ...and outside of the scope it doesn't
    EXPECT_CALL(obj, FourthMethod);
    EXPECT_CALL(obj, ThirdMethod);

    SomeFunctionToTest(obj);
}
Enter fullscreen mode Exit fullscreen mode

Sequence object

To gain some flexibility, you can create a dedicated Sequence object which then can be passed when calling EXPECT_CALL macro or to any other function as an input argument:

TEST(TestSomeFunction, CallingOrderIsCorrect)
{
    SomeMock obj;
    Sequence seq;

    // these functions must be called in order...
    EXPECT_CALL(obj, FirstMethod).InSequence(seq);
    EXPECT_CALL(obj, SecondMethod).InSequence(seq);

    // ...and these not necessarly
    EXPECT_CALL(obj, FourthMethod);
    EXPECT_CALL(obj, ThirdMethod);

    SomeFunctionToTest(obj);
}
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay