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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?