Nishanth Menon
Nishanth Menon

Reputation: 17

Passing two arrays as arguments in a gtest

I need to write a unit test (gtest) which passes two values from arrays a[] and b[] respectively.

Example:

a[] = {40, 45, 50 ,55, 60}
b[] = {2, 3, 5, 8, 9, 11}

My test case will pass these arrays (a[],b[]) as arguments to a function.

Is there a way I can pass both the arrays into a test case ?

Upvotes: 1

Views: 1295

Answers (2)

enders_uu
enders_uu

Reputation: 55

In case of more than 2 arrays are required.

#include "gtest/gtest.h"

using namespace std;

class MyTest : public testing::TestWithParam<tuple<vector<int>, vector<string>, vector<double>>> {

protected:
    virtual void SetUp() {
        cout << "{";
    }

    virtual void TearDown() {
        cout << "}" << endl;
    }

};

TEST_P(MyTest, TestP1) {
    auto [p1, p2, p3] = GetParam();
    for (auto v1: p1) cout << v1 << ",";
    for (auto v2: p2) cout << v2 << ",";
    for (auto v3: p3) cout << v3 << ",";
}

INSTANTIATE_TEST_SUITE_P(ParaGroupName,
                         MyTest,
                         testing::Values(
                                 make_tuple(vector<int>{1, 2}, vector<string>{"a1", "b1"}, vector<double>{1., 2.}),
                                 make_tuple(vector<int>{11, 12}, vector<string>{"a2", "b2"}, vector<double>{11., 12.})
                         )
);

// {1,2,a1,b1,1,2,}
// {11,12,a2,b2,11,12,}

Upvotes: 0

Tobias Wollgam
Tobias Wollgam

Reputation: 789

Expecting the arrays are static then you can pass them like the following example shows:

class ArrayTests : public UnitTest_SomeClass,
    public testing::WithParamInterface<std::pair<int*, int*>>
{ 
};

TEST_P(ArrayTests, doSomething)
{
    const auto pair = GetParam();
    const auto a = pair.first;
    const auto b = pair.second;

    EXPECT_EQ(4, a[3]);
    EXPECT_EQ(6, b[4]);
}

int a[]{ 1,2,3,4 };
int b[]{ 2,3,4,5,6 };

INSTANTIATE_TEST_CASE_P(UnitTest_SomeClass, ArrayTests, testing::Values(std::make_pair(a, b)));

You can now pass different arrays to the test:

int a0[]{ 1,2,3,4 };
int b0[]{ 2,3,4,5,6 };
int a1[]{ 7,8,9,10 };
int b1[]{ 2,3,4,5,6 };

INSTANTIATE_TEST_CASE_P(UnitTest_SomeClass, ArrayTests, testing::Values(std::make_pair(a0, b0), std::make_pair(a1, b1)));

I think it would be easier to use std::vector here for the int arrays, cause you got access to the number of elements. HTH

Upvotes: 2

Related Questions