[英]how to cause bad_alloc
我必須為我的單元測試造成bad_alloc(基本上,對於100%的代碼覆蓋率,我無法更改某些功能)。 我該怎么辦?
這是我的代碼示例。 我必須在這里某處導致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;
};
您可以在單元測試中明確地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";
}
}
您可以利用重載特定於類的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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.