I can successfully set and access privateData in the SetUp() method, but when I try to do the same in a TEST_F function, the value does not seem to update as expected. The TestPrivateDataSetting test fails, indicating that the value is still 42, not 100 as intended.
I suspect there might be an issue with how I’m accessing or modifying the private member from the test cases, but given the setup, it should be permissible due to the friend class declaration.
Question:
What could be causing this inability to set the private member from within the TEST_F functions? Is there a mistake in how I’ve set up the test fixture or in my understanding of the friend class mechanism in C++?
#ifndef A_H
#define A_H
class A {
friend class testsA; // Friend class declaration
private:
int privateData;
public:
A() : privateData(0) {}
void setPrivateData(int data) { privateData = data; }
int getPrivateData() const { return privateData; }
};
#endif // A_H
#ifndef TESTS_A_H
#define TESTS_A_H
#include "A.h"
#include <gtest/gtest.h>
class testsA : public testing::Test {
public:
A* a_instance; // Public member instance of A
protected:
void SetUp() override {
a_instance = new A();
a_instance->setPrivateData(42); // Set private member in SetUp
}
};
#endif // TESTS_A_H
#include "testsA.h"
TEST_F(testsA, TestPrivateDataSetting) {
// Trying to access and set private data in the test case
a_instance->setPrivateData(100);
ASSERT_EQ(a_instance->getPrivateData(), 100);
}
TEST_F(testsA, EnsureSetUpValueAccessible) {
// This will access the value set in SetUp
ASSERT_EQ(a_instance->getPrivateData(), 42);
}