I would like the test fixture method utFooFixture::utMethod1
to access the private member Foo::m_fooProc
.
I've followed the instructions and some other stack overflow advice to declare utFooFixture
as a friend using the FRIEND_TEST macro but I still get an access error inside utMethod1
. Why is this happening?
The access is supposed to be enabled by defining the UNITTESTS
preprocessor directive, which I have done for the project that contains Foo.h
and for the unit test project that contains utFoo.cpp
.
Foo.h
#ifdef UNITTESTS
#include <gtest/gtest_prod.h>
#endif
#include <Windows.h> // PROCESS_INFORMATION
class Foo
{
// Private member the unit test `utFooFixture::utMethod1` method needs to access
PROCESS_INFORMATION m_fooProc;
public:
void LaunchProcess() { // Uses m_fooProc to run a windows app }
void TerminateProcess() { // Uses m_fooProc to close a windows app }
#ifdef UNITTESTS
public:
FRIEND_TEST(utFooFixture , FooStartsAndClosesProcess); // VS Warns "VCR001: Function definition for 'FRIEND TEST' not found".
#endif
};
utFoo.cpp
#include "gtest/gtest.h"
#include "Foo.h"
class utFooFixture : public testing::Test
{
public:
void SetUp() {...}
void TearDown() {}
bool utMethod1(Foo &foo)
{
// Call Foo's public interface
foo.LaunchProcess();
DWORD status;
GetExitCodeProcess(foo.m_fooProc.hProcess, &status); // "Error: Foo::m_fooProc is inaccessible"
// Process launched successfully
if (status == 0) {
return true;
}
return false;
}
};
TEST_F(utFooFixture, FooStartsAndClosesProcess)
{
Foo f1;
bool launchWasSuccessful = utMethod1(f1);
ASSERT_EQ(launchWasSuccessful , true);
}
FRIEND_TEST(utFooFixture, FooStartsAndClosesProcess)
declares a class of the test case to be a friend. But you are trying to access Foo::m_fooProc
from the class utFooFixture
that should be a friend.
#ifdef UNITTESTS
- public:
- FRIEND_TEST(utFooFixture , FooStartsAndClosesProcess); // VS Warns "VCR001: Function definition for 'FRIEND TEST' not found".
+ friend class utFooFixture;
#endif
BTW public:
to friend declarations is not necessary.