google / google/googletest

Callback Data Overridden in Nested Calls

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

Description

**Bug Report: Unexpected Behavior in gtest v1.11.0**

**Environment:** Ubuntu-22.04

**Issue Description:**

When using gtest v1.11.0, I've encountered unexpected behavior when attempting to wrap the `Invoke` function within a test case. The issue arises when the first entrance `data` is overridden by the second call, leading to incorrect output.

**Example Code:**

**Working Example:**

```
TEST_F(readTest, testNestedCallback)
{
EXPECT_CALL(*mockedDev,
read(::testing::_),
::testing::_)
.WillOnce(::testing::Invoke(
[](uint8_t,
const std::function)>& callback) {
callback(std::span({1}));
}));
EXPECT_CALL(*mockedDev,
read(::testing::_, ::testing::_))
.WillOnce(::testing::Invoke(
[](uint8_t,
const std::function)>& callback) {
callback(std::span({2}));
}));

ptr->getNested(
[](std::string&& actual) { EXPECT_EQ(actual, "0x102");});
}
```

**Failed Example:**

```
void expect(std::span data)
{
EXPECT_CALL(*mockedDev,
read(::testing::_),
::testing::_)
.WillOnce(::testing::Invoke(
[data](uint8_t,
const std::function)>& callback) {
callback(data);
}));
}

TEST_F(readTest, testNestedCallback)
{
expect(std::span ({1}));
expect(std::span ({2}));

ptr->getNested(
[](std::string&& actual) { EXPECT_EQ(actual, "0x102");});
}
```

**Observed Output:**

The `actual` output is "0x202", which indicates that the first entrance `data` is overridden by the second call.

**Questions:**

1. Is this expected behavior?
2. Is there any alternative approach that can achieve the same functionality without overriding the first entrance `data`?

**Reference:**

I found a similar thread [here](https://github.com/google/googletest/issues/2389), but it doesn't seem to address this specific issue.

Contributor guide

Open the contributing guide

Research direction

No repository file or test is named. Start by reproducing the nested callback case from the issue, then inspect GoogleTest's Invoke and expectation-action behavior and compare the referenced issue 2389; done requires determining whether the observed result is expected and documenting or implementing a supported alternative.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
testing-qa
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.