googletest 中部分排序模拟调用的多个先决条件

Multiple prerequisites in partially ordered mock calls in googletest

我正在阅读 googletest here 的部分排序调用,我理解他们的示例是如何工作的。所以我们可以使用:

using ::testing::Sequence;
...
  Sequence s1, s2;

  EXPECT_CALL(foo, A())
      .InSequence(s1, s2);
  EXPECT_CALL(bar, B())
      .InSequence(s1);
  EXPECT_CALL(bar, C())
      .InSequence(s2);
  EXPECT_CALL(foo, D())
      .InSequence(s2);

显示以下DAG:

       +---> B
       |
  A ---|
       |
       +---> C ---> D

但我想知道我们如何定义一个调用的多个先决条件。例如,如何为以下 DAG 中的 E 节点添加 DAG 约束?

       +---> B ----------+
       |                 |
  A ---|                 |---> E
       |                 |
       +---> C ---> D ---+

会是这样吗?

using ::testing::Sequence;
...
  Sequence s1, s2, s3;

  EXPECT_CALL(foo, A())
      .InSequence(s1, s2);
  EXPECT_CALL(bar, B())
      .InSequence(s1, s3);
  EXPECT_CALL(bar, C())
      .InSequence(s2);
  EXPECT_CALL(foo, D())
      .InSequence(s2, s3);
  EXPECT_CALL(foo, E())
      .InSequence(s3);

您可以使用 After 方法在某些其他调用之后期待一些调用。 https://google.github.io/googletest/reference/mocking.html#EXPECT_CALL.After

所以在你的情况下它会是这样的:

Mocked mock;
Sequence s1, s2;
EXPECT_CALL(mock, A).InSequence(s1, s2);
Expectation exp_b = EXPECT_CALL(mock, B).InSequence(s1);
EXPECT_CALL(mock, C).InSequence(s2);
Expectation exp_d = EXPECT_CALL(mock, D).InSequence(s2);
EXPECT_CALL(mock, E).After(exp_b, exp_d);

完整的可运行示例:

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

using ::testing::Sequence;
using ::testing::Expectation;

class Mocked {
public:
    MOCK_METHOD(void, A, ());
    MOCK_METHOD(void, B, ());
    MOCK_METHOD(void, C, ());
    MOCK_METHOD(void, D, ());
    MOCK_METHOD(void, E, ());
};

TEST(Sequences, ABCDE)
{
    Mocked mock;
    Sequence s1, s2;
    EXPECT_CALL(mock, A).InSequence(s1, s2);
    Expectation exp_b = EXPECT_CALL(mock, B).InSequence(s1);
    EXPECT_CALL(mock, C).InSequence(s2);
    Expectation exp_d = EXPECT_CALL(mock, D).InSequence(s2);
    EXPECT_CALL(mock, E).After(exp_b, exp_d);

    mock.A();
    mock.B();
    mock.C();
    mock.D();
    mock.E();
}

P.S。您可以将 InSequence 完全替换为 After 以获得更简单的代码。