如何测试只修改私有类成员变量的void方法? [英] How to test void method that only modifies private class member variables?

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

问题描述

我正在尝试对初始化一些私有字段的类中的方法进行单元测试:

I'm trying to unit test a method in a class that initializes some private fields:

public void init(Properties props) throws Exception {

    this.language = props.getProperty(Constants.LANGUAGE,Constants.LANGUAGE_DEFAULT);   
    this.country = props.getProperty(Constants.COUNTRY,Constants.COUNTRY_DEFAULT);

        try {
            this.credits = Integer.valueOf(props.getProperty(Constants.CREDITS_OPTION_NAME, Constants.CREDITS_DEFAULT_VALUE));
        } catch (NumberFormatException e) {
            throw new Exception("Invalid configuration: 'credits' does not contain a valid integer value.", e);
        }
        //rest of method removed for sake of simplicity
    }

我的困境是我想断言语言、国家和信用字段在调用 init 后已经设置,但是它们是私有的,没有公共访问器方法.我看到有两种测试解决方案:

My dilemma is that I want to assert that the language, country and credits fields have been set after calling init, however they are private with no public accessor methods. I see there are two solutions for testing this:

  1. 创建访问私有字段的公共方法,然后在测试 init 方法后调用这些方法.
  2. 让单元测试只调用 init 方法,并假设一切正常,没有抛出异常.

您认为测试此方法的理想方法是什么?

What do you think is the ideal way to test this method?

推荐答案

我想断言调用init后语言、国家和信用字段已经设置

I want to assert that the language, country and credits fields have been set after calling init

一些哲学:你为什么要关心它们是否设置正确?如果答案是因此该类的行为正确",那么您可以通过测试预期的后续行为来测试它们是否已正确设置.但是,如果它们设置不正确没有任何效果,它们就是多余的,您应该将其删除.

Some philosophy: why do you care whether they are set correctly? If the answer is "so the class then behaves correctly", then you can test that they have been set correctlty by testing that expected subsequent behaviour. If however setting them incorrectly has no effect they are redundant and you should remove them.

另一位发帖人建议使用反射来访问私有字段.我建议不要这样做;任何标记为私有的都应该是类的实现细节,因此不应直接测试.您应该改为测试您的类的已发布 API.然后,您可以通过更改实现(私有)细节轻松地对其进行重构.

Another poster has suggested using reflection to access the private fields. I advise against this; anything marked private should be an implementation detail of the class, and therefore should not be directly tested. You should instead test the published API of your class. You then have the freedom to refactor it easilly by changing implementation (private) details.

这篇关于如何测试只修改私有类成员变量的void方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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