Unrecognized Escape Sequence

An increasingly grumpy blog about software engineering

A couple of Google Test gotchas

Testing multiple calls to the same mock method

Situation: You want to test that a method of your mocked dependency is called multiple times with different parameters. For example, in the following code snippets we are testing that a method setProperty is called twice from within the method being tested. As we typically want to check only one thing per test, we would have two tests which EXPECT_CALL these calls:

EXPECT_CALL(*m_mockScreen, setProperty("searchBox", "text", "some text")).Times(Exactly(1));
EXPECT_CALL(*m_mockScreen, setProperty("comboBox", "text", "some text")).Times(Exactly(1));

However, both these tests fail. The framework doesn’t know which of the two calls is the one we’re actually testing in each case, and as two two calls have different parameters, a failure is reasonable. In this case, we need to tell the testing framework to expect the other call, otherwise it quite reasonably fails:

EXPECT_CALL(*m_mockScreen, setProperty(_, _, _)).Times(Exactly(1));
EXPECT_CALL(*m_mockScreen, setProperty("searchBox", "text", "some text")).Times(Exactly(1));
EXPECT_CALL(*m_mockScreen, setProperty(_, _, _)).Times(Exactly(1));
EXPECT_CALL(*m_mockScreen, setProperty("comboBox", "text", "some text")).Times(Exactly(1));

Testing overloaded method calls

The following test fails to compile because the runCommand method is overloaded in the interface implemented by m_mockOsHelper, and the compiler doesn’t know which overload to apply given that some of the parameters are undefined _.

EXPECT_CALL(*m_mockOsHelper, runCommand("/usr/bin/some_command", _, _)).Times(Exactly(1));

So we need to provide typed undefined parameters, such as:

EXPECT_CALL(*m_mockOsHelper, runCommand("/usr/bin/some_command", A<int>(), _)).Times(Exactly(1));

Kindly, the good folks down at Google also added the An<>() variant of this, so we can get our grammar in order!

EXPECT_CALL(*m_mockOsHelper, runCommand("/usr/bin/some_command", An<int>(), _)).Times(Exactly(1));