2

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;
};
  • Try allocating a ridiculously large array of your Value. – Anon Mail Oct 04 '15 at 16:16
  • @AnonMail the problem is, i will need only one Value, if there is no bad_alloc. – Наталья Шашок Oct 04 '15 at 16:19
  • 1
    You are trying to do a stress-test as a unit test. This approach is not usually recommended, and moreover, it is difficult to achieve without adding some code, at least using compiler directives, such as #ifdef TEST_3 etc. – A.S.H Oct 04 '15 at 16:50

2 Answers2

3

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());
}
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
0

You can just explicitly throw a std::bad_alloc in your unit test. For example

#include <iostream>
#include <new>

void test_throw()
{
    throw std::bad_alloc();
}

int main()
{
    try
    {
        test_throw();
    }
    catch (std::bad_alloc& ba)
    {
        std::cout << "caught";
    }
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • I can't change any functions, and i can pass only a Value parameter in this function. – Наталья Шашок Oct 04 '15 at 16:30
  • 2
    The only way to cause a `std::bad_alloc` other than to `throw` it would be to call `insert` in a `while` loop over and over until you run out of memory. I wouldn't recommend that because you will leak all those pointers and probably crash other things while using all that memory. – Cory Kramer Oct 04 '15 at 16:33