Search code examples
c++arrayscppunit

Char array initialisation in class


I am trying to unit test a C++ application that I am building and I'm having an issue initializing the array when used in a class. I've tried alot of different methods of loading this information, the only ones that work are inefficient / not suitable.

Here is the hex array that I have (randomised the parts)

0x24,0x54,0x3b,0x72,0x8b,0x03,0x24,0x29,0x23,0x43,0x66,0x22,0x53,0x41,0x11,0x62,0x10

And header file for my unit test:

class MessageParsingTest : public CPPUNIT_NS::TestFixture {
    CPPUNIT_TEST_SUITE(MessageParsingTest);

    CPPUNIT_TEST(testIdentifyFirstMessageType);

    CPPUNIT_TEST_SUITE_END();

public:
    MessageParsingTest();
    virtual ~MessageParsingTest();
    void setUp();
    void tearDown();

private:
    void testIdentifyFirstMessageType();
    void testIdentifySecondMessageType();

    // data members for the hex array
    unsigned char firstMessage[1500]; 
};

Then in my test case setUp function;

void MessageParsingTest::setUp() {
    firstMessage = {0x24,0x54,0x3b,0x72,0x8b,0x03,0x24,0x29,0x23,0x43,0x66,0x22,0x53,0x41,0x11,0x62,0x10};
}

That it my latest failed attempt, it says its not valid during compilcation, as I expected, but at this point I was trying anything.

I've also tried things like (all in setUp function)

firstMessage << "\0x24\0x54\0x3b\0x72\0x8b\0x03\0x24\0x29\0x23\0x43\0x66\0x22\0x53\0x41\0x11\0x62\0x10";

firstMessage[1500] = "\0x24\0x54\0x3b\0x72\0x8b\0x03\0x24\0x29\0x23\0x43\0x66\0x22\0x53\0x41\0x11\0x62\0x10";

and a few other crazy ways, Does anyone know the proper way to load this data? the only way I've had it working so far is with either no data member declaration and straight up defining it and initializing in one line (but then I cant access in the test cases) or doing it one by one like firstMessage[0] = 0x24; etc.

I understand that there will be a simple, proper way of doing this and considering what the application actually does, this part should be the easiest.


Solution

  • You have few options:

    1. Initialize arrays in constructor MesssageParsingTest using syntax : firstMessage{0x24,0x54,0x3b,0x72,0x8b,0x03,0x24,0x29,0x23,0x43,0x66,0x22,0x53,0x41,0x11,0x62,0x10} in initializer list.
    2. Create static const array containing your message, and either copy it to member variable using memcpy, or use static member and get rid of firstMessage member variable.

    Declare const static member in .h inside class definition:

    static const unsigned char kFirstMessage[];
    

    and define + initialize it in .ccp

    const unsigned char MessageParsingTest::kFirstMessage[] = "\0x24\0x54\0x3b\0x72\0x8b\0x03\0x24\0x29\0x23\0x43\0x66\0x22\0x53\0x41\0x11\0x62\0x10";
    

    I would prefer static const member if you do not intend to modify this array later, since it makes the intention cleaner.