CppUnitTestFramework: Variable value set in TEST_CLASS_INITIALIZE does not persist in TEST_METHOD

432 views Asked by At

I have a std::string declared in my TEST_CLASS that should be initialized once for the class that is to be used in two other TEST_METHODs.

However, when TEST_CLASS_INITIALIZE is called (which does run before any TEST_METHOD), projectDirectory is properly set. Yet, the issue is that when I debug what the value is of projectDirectory in each TEST_METHOD, the value is an empty string ("").

What am I doing incorrectly?

#include "pch.h"
#include "CppUnitTest.h"
#include "../Project/ConfigurationManager.h"
#include <string>

#define STRINGIFY(x) #x
#define EXPAND(x) STRINGIFY(x)

using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace Project;

TEST_CLASS(ConfigurationManagerUnitTests) {

public:
    std::string projectDirectory;

private:

    TEST_CLASS_INITIALIZE(ConfigurationManagerUnitTestInitialization) {
        std::string projectDirectory = EXPAND(UNITTESTPRJ); // UNITTESTPRJ preprocessor def. equal to Project directory
        projectDirectory.erase(0, 1); // remove 1st quotation mark
        projectDirectory.erase(projectDirectory.size() - 2); // remove closing quotation mark & period symbol
    }

    TEST_METHOD(ConfigurationFileProcessing) {
        ConfigurationManager* manager = ConfigurationManager::getConfiguration();

        Assert::IsFalse(manager->ProcessConfigurationFile(projectDirectory + "Configuration1.ini"));
        Assert::IsTrue(manager->ProcessConfigurationFile(projectDirectory + "Configuration2.ini"));
        Assert::IsTrue(manager->ProcessConfigurationFile(projectDirectory + "Configuration3.ini"));
        Assert::IsTrue(manager->ProcessConfigurationFile(projectDirectory + "Configuration4.ini"));
    }

    TEST_METHOD(ConfigurationFileInitialization) {
        ConfigurationManager* manager = ConfigurationManager::getConfiguration();

        Assert::IsTrue(manager->InitializeConfiguration(projectDirectory + "Configuration5.ini"));
    }

};

P.S. I did look at this post that is similar, but my problem is that projectDirectory is an empty string even the first method that uses the string.

1

There are 1 answers

1
Chris Olsen On BEST ANSWER

There are at least a couple of issues with your example code.

  1. You are declaring a local variable projectDirectory in the TEST_CLASS_INITIALIZE, which hides the class member projectDirectory.

  2. TEST_CLASS_INITIALIZE cannot be used to initialize class members (unless they are declared as static). You should use TEST_METHOD_INITIALIZE for this.