googletest中部分有序模拟调用的多个先决条件
Posted
技术标签:
【中文标题】googletest中部分有序模拟调用的多个先决条件【英文标题】:Multiple prerequisites in partially ordered mock calls in googletest 【发布时间】:2022-01-18 15:05:24 【问题描述】:我正在阅读 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);
【问题讨论】:
【参考方案1】:您可以使用 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();
附:您可以将 InSequence
完全替换为 After
以获得更简单的代码。
【讨论】:
以上是关于googletest中部分有序模拟调用的多个先决条件的主要内容,如果未能解决你的问题,请参考以下文章