How do I mock time and random sources?

Mocking time and random sources is essential for testing in C++. It allows you to control the flow of time and produce predictable outcomes for randomness, ensuring consistent test results.

Mocking, Time, Randomness, C++, Testing, Unit Tests

// Example of mocking time and random generation in C++ #include #include #include class TimeProvider { public: virtual std::time_t getCurrentTime() { return std::time(nullptr); } }; class RandomGenerator { public: virtual int getRandomNumber(int min, int max) { return min + std::rand() % ((max + 1) - min); } }; void testWithMockedTimeAndRandom() { TimeProvider timeProvider; // Replace with a mock in tests RandomGenerator randomGenerator; // Replace with a mock in tests // Use timeProvider and randomGenerator in your logic std::cout << "Current Time: " << timeProvider.getCurrentTime() << std::endl; std::cout << "Random Number: " << randomGenerator.getRandomNumber(1, 100) << std::endl; }

Mocking Time Randomness C++ Testing Unit Tests