我有一个 C++ 11 header ,它的常量值声明为 my_const_value
。还有一个名为 GetValue
的函数,它使用 const 值运行复杂逻辑并返回预期值。
我想用 my_const_value
的不同值对 GetValue
进行单元测试。
我知道这是不可取的,但为了为 GetValue
编写单元测试,我希望使用不同的 my_const_value
值来测试 GetValue
。 C++ 中是否有一些 hack-ish 方法来更改 const 的值,即使它是 const?
//MyHeader.hpp
namespace myheader {
const int my_const_value = 5;
int GetValue() {
// In real-world, lets say below line of code is a complex logic that needs to be tested by a unit test
return /my_const_value * 5) / 25;
}
}
#include "MyHeader.hpp"
#include <gtest/gtest.h>
TEST(MyHeaderTest, Testing_Something) {
EXPECT_EQ(1, myheader::GetValue()); // This is okay
// I want to test that in the future is the value of my_const_value changes to something else then
// myheader::GetValue returns the expected result. But of course, I cannot change my_const_value because it is a const.
// Is there a way to hack around this for a unit test? Is there a way that I could still hack and change the value of my_const_value?
myheader::my_const_value = 25;
EXPECT_EQ(5, myheader::GetValue());
}
我知道我可以const_cast
my_const_value
到一个非常量变量。但这在这里无济于事。如果有一些 hack 可以通过使用指针或其他东西来更改 my_const_value
的值,那将回答我的问题。
最佳答案
没有。
更改声明为 const
的值会调用未定义的行为。为了便于说明,请考虑这段代码
const int x = 4;
modify_const_somehow(x,42); // "magically" assigns 42 to x
std::cout << x;
可以打印任何东西。您可以在控制台上看到 4
或 42
,但是 "Hey you broke the rules, const cannot be modified"
将是一个有效的输出,因为出色地。无论您如何修改 x
,该代码都有未定义的行为。编译器不需要发出错误或警告,代码只是无效的,编译器没有义务对它做任何有意义的事情。
唯一允许移除常量的情况是当对象实际上不是常量时。听起来很奇怪不是吗?看这个例子:
const int x = 42;
int y = 100;
void foo(const int& a) {
const_cast<int&>(a) = 4;
}
foo(x); // undefined behavior !!
foo(y); // OK !!
您的问题的解决方案是编写可测试的代码。例如:
int GetValue(int value = my_const_value) {
// In real world, lets say below line of code is a complex logic that needs to be tested by a unit test
return (value * 5) / 25;
}
如果您想保留原始签名,您也可以将其包装(如评论中所建议):
int GetValue_impl(int value) {
return (value * 5) / 25;
}
int GetValue() {
return GetValue_impl(my_const_value);
}
现在您可以测试 GetValue_impl
而 GetValue
使用常量。但是,我真的很奇怪你为什么要测试一个不可能发生的案例。
关于c++ - 对于单元测试,是否有一种骇人听闻的方法来更改 const 变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63593246/