gpt4 book ai didi

c++ - 单元测试 - 设置私有(private)成员以获得所需的对象状态

转载 作者:可可西里 更新时间:2023-11-01 16:39:35 28 4
gpt4 key购买 nike

我正在迈出单元测试的第一步,但遇到了封装问题。我的类有一些私有(private)成员变量不应该对客户端可见,但为了让我将对象置于我想要测试它的状态,我需要设置这些私有(private)变量。

假设我有这样的代码:

Class Foo {

public:
int action() ;
private:
int state ;

} ;

int Foo::action()
{
if(this->state == 1)
return 1 ;
else
return 0 ;
}

所以现在我想测试 Foo::action(),但我需要能够设置 Foo::state 以便能够在不同的情况下检查功能场景。一种解决方案是在测试代码中使用邪恶的“define private public”。但是还有更优雅的东西吗?我想强调 Foo::state 是一个不应被客户端访问的变量,因此我不想声明任何公共(public) setter。

编辑:

我现在认为扩展我想在测试代码中测试的类并在该派生类中包含 setter 是可行的,前提是我将私有(private)变量更改为 protected 。但这是“仅限一代”的解决方案,仍然感觉像是一种 hack,而不是一种正确的方法。

编辑 2:

阅读答案和评论后(特别感谢 Lieven 和 ap。)我相信我现在尝试测试的实际类(class)(不是我提供的简单示例)只是做了太多,而我的答案问题是将它的一些逻辑移动到另一个将由大人物使用的类中。

最佳答案

只有两种可能性(搁置重构)

  1. 使用公共(public)接口(interface)设置状态。
  2. 如果您不能通过公共(public)接口(interface)设置它,则该状态是多余的

选项 2 不言自明,很可能不适用于您的情况,因此您只能通过类的公共(public)接口(interface)设置状态。

正如您已经提到的,这是可能的,但需要大量代码才能达到正确的状态。这本身可能表明您的类(class)目前正在做很多事情,是时候将类(class)的一部分重构为更小的、可测试的类(class)了。

来自 Do not test private methods

If you find the need to test a private method, then you’re doing something else wrong. There is an “upstream” problem, so to speak. You have arrived at this problem due to some other mistake previous in this process. Try to isolate what that is, exactly, and remove that rather than bending your tests to go down a painful road of brittleness in testing.

Unit testing private members

I'd recommend not unit testing private methods. Since they're private, they may be changed in any conceivable (or inconceivable?) manner between each release. If a given private method is so critical to the operation of the class that you feel it deserves test cases, then it's probably time to refactor that out into a protected or public method

一个常见的引用是

You should never touch your privates

关于c++ - 单元测试 - 设置私有(private)成员以获得所需的对象状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13971717/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com