Search code examples
unit-testingtddgoogletest

Unit testing: Am I doing right when using another method in unit testing a method?


To my best knowledge, unit testing should be done on each public API separately. But, I have been experiencing with a situation in which I have not found out a clear way to unit test each API independently as shown in the following example:

class MyStorage {
private:
    std::vector<int> int_vec_;

public:
    bool insert_int(int value);
    int get_value_at(int idx);
}

I used GooogleTest framework and wrote unit tests as follows:

int int_tenth(int x) { return x * 10; }

TEST_F(MyStorageTest, insert_int) {
    for(int i = 0; i < 10; i++) {
        int value = int_tenth(i);
        bool ret = my_storage.insert_int(value);
        ASSERT_TRUE(ret);
    }
}

TEST_F(MyStorageTest, get_value_at) {
    for(int i = 0; i < 10; i++) {
        int value = int_tenth(i);
        my_storage.insert_int(value);
    }

    for(int i = 0; i < 10; i++) {
        int expected_value = int_tenth(i);
        int value = my_storage.get_value_at(i);
        ASSERT_EQ(expected_value, value);
    }
}

Am I doing right? If not, how can I make unit tests for this example?


Solution

  • I think this looks "okay". Your test case is exercising both APIs - and yes, you need to use the insert method in order to test the get method.

    What is missing: corner cases, especially for get. Like: having test cases for negative indixes. Or invalid indexes. Such tests should result in certain errors - and you might want to make sure that the expected errors (for example exceptions) show up.

    Beyond that you might want to look into libraries that are based on the QickCheck idea (where the test framework runs random tests to find violations of properties that you specify for your production code).