具有许多私有方法的Java测试类 [英] Java test class with many private methods

查看:149
本文介绍了具有许多私有方法的Java测试类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级负责将合同从CSV导入数据库.

I have a class that has the responsibility of importing contracts from a CSV to database.

该类本身只有一个开始导入的公共方法,而其他方法都是私有的(因为只有该类本身将使用,并且它们保留逻辑).

The class itself has only one public method that starts the import and the other methods are all private (because only the class itself will use, and they hold the logic).

我开始使用Spock对该类进行测试,并且有许多私有方法,我应该如何对其进行测试?

I'm starting to make tests for this class using Spock and there are many private methods, how should I test it?

我应该将它们公开进行测试吗?仅测试主要方法,公开方法?

Should I turn them into public to test? Test only the main method, the public one?

什么是最好的?

推荐答案

从理论上讲,您的私有方法最终会被一种公共方法使用,否则根本就不会使用它们.因此,通常,您将测试设置为在必要的上下文中调用公共方法,以使其击中您的私有方法.

In theory, your private methods are being used ultimately by one of the public methods, or else they're not used at all. So typically you setup your tests to call the public methods with the necessary context so that it hits your private methods.

单元测试主要是测试编译单元(即类).您可以直接对测试方法进行单元化,但是必须将它们公开,这不利于拥有一个简洁的API.

The unit tests are primarily testing the compilation unit (i.e. the class). You can unit test methods directly but then they have to be public, which goes against having a nice clean API.

因此,请对您的公共方法进行足够的测试,以使用所有私有方法.私有方法是此类的内部机制,不需要直接进行测试.

So test your public method enough to hit all the private methods. Private methods are internal mechanics of the class, they don't need to be tested directly.

这篇关于具有许多私有方法的Java测试类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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