2015-10-04 29 views
1

我必須爲我的單元測試導致bad_alloc(基本上,對於100%的代碼覆蓋率,我無法更改某些函數)。我該怎麼辦?
這是我的代碼示例。我必須在這裏導致bad_alloc。如何導致bad_alloc

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; 
}; 
+0

嘗試分配大的離譜陣列的價值。 –

+0

@AnonMail問題是,如果沒有bad_alloc,我只需要一個值。 –

+1

你正試圖做一個單元測試的壓力測試。通常不建議使用這種方法,而且,如果不添加某些代碼,至少使用編譯器指令(如#ifdef TEST_3等)就很難實現。 –

回答

1

你可以明確地throw一個std::bad_alloc在你的單元測試。例如

#include <iostream> 
#include <new> 

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

int main() 
{ 
    try 
    { 
     test_throw(); 
    } 
    catch (std::bad_alloc& ba) 
    { 
     std::cout << "caught"; 
    } 
} 
+0

我無法更改任何函數,並且只能傳遞一個Value參數在這個功能。 –

+0

除了'throw'之外,導致'std :: bad_alloc'的唯一方法是反覆調用'while'循環中的'insert',直到內存不足。我不會推薦這麼做,因爲你會泄漏所有這些指針,並可能在使用所有內存時崩潰其他東西。 – CoryKramer

1

您可以利用的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()); 
}