如何对私有变量进行单元测试?

编程入门 行业动态 更新时间:2024-10-28 08:24:41
本文介绍了如何对私有变量进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑一个链表类,我维护2个私有变量1. firstNode和2. lastNode.这些变量仅供内部使用,不能通过吸气剂公开.我想测试操作是否确实按预期修改了这两个变量.例如:如果最后一个节点是重复项,则在排序后的链表中消除重复项应该更改最后一个节点.

Consider a linkedlist class and I maintain 2 private variables 1. firstNode and 2. lastNode. These variables are only for internal use thus, not exposed via getters. I want to test that operations do modify these 2 variables as expected. Eg: eliminating duplicate in sorted linkedlist should change the last node if last node was a duplicate.

  • 我应该只为单元测试添加一个显式的getter吗?

  • Should I add an explicit getter only for unit tests?

    如果没有,那么如何访问未公开的私有变量的值?

    If not then how to access the value of private unexposed variables ?

    推荐答案

  • 不.
  • 你不知道.您会将测试与实现耦合起来.如果您要重构实现,那么您将有信心,如果您的测试在不进行修改的情况下仍能正常工作,那么您不会破坏任何东西.
  • 考虑如果这些变量未正确更新,会出什么问题(即违反合同的哪一部分).为此编写一个测试,证明它在应有的情况下会失败,然后确保它不会失败.

    Think about what will go wrong (i.e. which part of the contract will be violated) if those variables are not correctly updated. Write a test for that, prove that it fails when it should, then make sure it doesn't fail.

    更多推荐

    如何对私有变量进行单元测试?

    本文发布于:2023-11-14 05:03:59,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1586297.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:变量   单元测试

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!