Home > Net >  C Overwrite initializer list in unit test
C Overwrite initializer list in unit test

Time:06-23

I have some C code like this that I want to unit test:

class Example
{
    private: 
        ExpensiveObject expensiveObject;
        
    public:
        Example() : expensiveObject() {
            ... constructor code
        }

        methodA() {
            ... some code
        }
}

To write a unit test for methodA I need to create an instance of Example. The problem is that I don't want to initialize expensiveObject, I would want to set it to null in my unit test (I am using Google Test). Is there a way to do it?

CodePudding user response:

expensiveObject cannot be assigned null. What you might want is to have a smart pointer to ExpensiveObject, and have multiple constructors or better you want to inject your dependencies.

class Example
{
    private: 
        std::shared_ptr<ExpensiveObject> expensiveObject;
        
    public:
        Example(std::shared_ptr<ExpensiveObject> ptr) : expensiveObject(ptr) {
            //... constructor code
        }

        methodA() {
            //... some code
        }
}

Now you can test it for null scenarios as well

Example ex{nullptr};
ex.methodA();

CodePudding user response:

I can't think of any way to do this without slightly modifying the definition of the Example class. However, if you can tolerate to do this, there are several ways to do this: dependency injection using pointers as the other answer mentioned, or templatizing the class as shown below:

// Used for production.
class ExpensiveObject {
  // Expensive stuff here
};

// Only used for testing.
class CheapObject {
  // Cheap stuff here
};

// Instantiate with ExpensiveObject for production and with CheapObject for
// testing.
template <class T>
class Example {
 private:
  T expensiveObject;

 public:
  Example() : expensiveObject() {}

  int methodA() { return 1; }
};

TEST(Example, Test1) {
  // CheapObject is used for testing.
  Example<CheapObject> example;
  EXPECT_EQ(example.methodA(), 1);
}

Live example: https://godbolt.org/z/7e1rhWY4b

  • Related