google / google/googletest

EXPECT_THAT with Throws invokes callable twice when exception is not thrown

Open
#4,073 14 comments 5 reactions 0 assignees View on GitHub
bug
Dominant language
C++
Stars
39.5k
Forks
10.9k
Avg merge
6d 13h
Merged PRs (30d)
1

Description

**Describe the bug**

`EXPECT_THAT` macro with the `Throws` expectation invokes the callable twice when it does not throw an exception. This does not happen when the exception is thrown.

This causes failures for stateful lambdas or lambdas with side effects.

**Steps to reproduce the bug**

Repro code:
```cpp
#include
#include
#include

int main()
{
int state = 1;
EXPECT_THAT(([&] { std::cout << "I am invoked " << state++ << '\n'; }),
testing::Throws());
}
```

Outputs:
```
I am invoked 1
I am invoked 2
...
```

Also see https://godbolt.org/z/WE44hn5Kc.

**Does the bug persist in the most recent commit?**

Yes.

**What operating system and version are you using?**

Does not matter. The issue happens on both Windows and Linux.

**What compiler and version are you using?**

MSVC 17.4.1, clang trunk.

Contributor guide

Open the contributing guide

Research direction

Start at the EXPECT_THAT entry point and the Throws expectation implementation, using the issue's stateful-lambda reproduction to trace each invocation. Add a regression test for a callable that does not throw and verify that it is invoked only once, while preserving the existing thrown-exception behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
testing-qa
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.