googlemock线程和序列中断

时间:2018-09-18 16:46:11

标签: c++ multithreading googletest googlemock

考虑一个类有多个实例的情况,有一些工作线程在做事情,每个线程使用一个唯一的实例。

考虑线程代码做一些简单的事情,例如:

thing->write("discover")
thing->read_until("\n", timeout)
thing->write("version")
thing->read_until("\n", timeout)

首先,我发现如果运行(非线程)测试(测试上述内容),测试将失败,例如:

EXPECT_CALL(thing, write("discover"));
EXPECT_CALL(thing, read_until("\n", timeout))
    .WillOnce(Return("hello");
EXPECT_CALL(thing, write("version"));
EXPECT_CALL(thing, read_until("\n", timeout));
    .WillOnce(Return("v99");

除非在测试开始时添加:

testing::InSequence dummy;

没有这个,我发现该模拟对于被测代码对read_until的每次调用都使用了第二次调用read_until的返回值,所以我得到了

write: discover
read: v99

失败。

好的,所以没问题,只需将InSequence位添加到每个测试中即可。

但是,如果我有多个启动的线程,则InSequence调用无法确定将首先进行哪个调用,因此(显然)破坏了测试。但是如果没有InSequence位,则测试也将失败,因为它始终使用最后设置的期望值。这有点烦人。我知道您可以在设置期望值时多次调用.WillOnce(Return(val)),但是还有其他方法吗?

我之所以问,是因为在此API中有很多调用以不同的顺序进行(在测试中的代码中)-每个期望都很好地包装在一个不错的辅助函数中,以减少测试中的代码重复,例如:

void discoverOk(thing)
{
    EXPECT_CALL(thing, write("discover"));
    EXPECT_CALL(thing, read_until("\n", timeout))
        .WillOnce(Return("hello");
}

void discoverError(thing)
{
    // simulate timeout, returns empty string:
    EXPECT_CALL(thing, write("discover"));
    EXPECT_CALL(thing, read_until("\n", timeout))
        .WillOnce(Return("");
}

很明显,在设置EXPECT_CALL时,多次使用.WillOnce(Return(...))效果不佳。

0 个答案:

没有答案