I have to cause bad_alloc for my unit test (basically, for 100% code coverage, there's no way i can change some functions). What should I do?
Here is my code example. I have to cause bad_alloc somewhere here.
bool insert(const Value& v) {
Value * new_value;
try {
new_value = new Value;
}
catch (std::bad_alloc& ba){
std::cerr << "bad_alloc caught: " << ba.what() << std::endl;
return false;
}
//...
//working with new_value
//...
return true;
};
You can exploit the possibility of overloading class-specific operator new:
#include <stdexcept>
#include <iostream>
#define TESTING
#ifdef TESTING
struct ThrowingBadAlloc
{
static void* operator new(std::size_t sz)
{
throw std::bad_alloc();
}
};
#endif
struct Value
#ifdef TESTING
: ThrowingBadAlloc
#endif
{
};
bool insert(const Value& v) {
Value * new_value;
try {
new_value = new Value;
}
catch (std::bad_alloc& ba){
std::cerr << "bad_alloc caught: " << ba.what() << std::endl;
return false;
}
//...
//working with new_value
//...
return true;
};
int main()
{
insert(Value());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With