如何对私有变量进行单元测试? [英] How to unit test a private variable?

查看:281
本文介绍了如何对私有变量进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个链表类,我维护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.

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

  1. Should I add an explicit getter only for unit tests?

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

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

推荐答案

  1. 不.
  2. 你不知道.您会将测试与实现耦合起来.如果您要重构实现,那么您将有信心,如果您的测试在不进行修改的情况下仍能正常工作,那么您不会破坏任何东西.

考虑如果这些变量未正确更新,会出什么问题(即违反合同的哪一部分).为此编写一个测试,证明它在应有的情况下会失败,然后确保它不会失败.

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.

这篇关于如何对私有变量进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆