Search code examples
c++unit-testingtype-safety

Check if the returned object is of expected subclass in C++ unit test


I have a function that returns object of abstract class.

AbstractClass some_function(int argument);

I have an assumption that if argument == 1 then some_function should return object of DerivedClassOne and if argument == 2 it should be DerivedClassTwo. I want to check these assumptions with a simple unit test.

What's the best (simple, readable, reliable and independent of any third-party libraries and tools) way to check that?


Solution

  • In your example, some_function() is returning an AbstractClass by value, which means the returned object gets sliced and will always be just a AbstractClass by itself. Polymorphism only works with pointers and references. Either way, you can use dynamic_cast for your validation check.

    For example:

    AbstractClass* some_function(int argument);
    
    ...
    
    AbstractClass *obj;
    
    obj = some_function(1);
    if (dynamic_cast<DerivedClassOne*>(obj) != NULL)
        // returned the correct type...
    else
        // returned the wrong type...
    
    obj = some_function(2);
    if (dynamic_cast<DerivedClassTwo*>(obj) != NULL)
        // returned the correct type...
    else
        // returned the wrong type...
    

    Or:

    AbstractClass& some_function(int argument);
    
    ...
    
    try {
        dynamic_cast<DerivedClassOne&>(some_function(1));
        // returned the correct type...
    }
    catch (const std::bad_cast&) {
        // returned the wrong type...
    }
    
    try {
        dynamic_cast<DerivedClassTwo&>(some_function(2));
        // returned the correct type...
    }
    catch (const std::bad_cast&) {
        // returned the wrong type...
    }