单元测试组合服务方法
我正在为一个类编写(junit)单元测试,该类使用以下方法实现公开接口:
public Set<Setting> getUserSettings();
public Set<Setting> getOrganizationSettings();
public Set<Setting> getDefaults();
public Set<Setting> getAllSettings();
从特定层获取设置的方法从各个位置执行 IO 来检索结果。 getAllSettings() 返回所有级别的所有设置的单个集合,其中“最高”级别具有优先权(即,如果默认和用户级别中存在设置,则将使用用户级别中的设置。
我已经已经为 getUserSettings()、getOrganizationSettings()、getDefaults() 编写了单元测试,用模拟对象模拟了 IO 操作
getAllSettings() 的实现看起来像这样
public Set<Setting> getAllSettings(){
Set<Setting> defaults = getUserSettings();
Set<Setting> custom = getOrganizationSettings();
Set<Setting> undefined = getDefaults();
//perform some sorting and business logic
//return fully sorted set
}
。我的问题在于如何对 getAllSettings() 方法进行单元测试。我是否对 user/organization/defaultSettings 方法使用的所有下游资源调用使用模拟(使用 easymock/powermock)? /更简单的方法来做到这一点。
I am writing (junit) unit tests for a class which implements an exposed interface with methods like:
public Set<Setting> getUserSettings();
public Set<Setting> getOrganizationSettings();
public Set<Setting> getDefaults();
public Set<Setting> getAllSettings();
The methods for getting Settings from a specific layer do IO from various places for retrieving their results. getAllSettings() Returns a single set of all the Settings at all levels, with the 'uppermost' level having preference (i.e. if a setting exists in the default and user level, the setting in the user-level will be used.
I've already written the unit tests for getUserSettings(), getOrganizationSettings(), getDefaults(), mocking out the IO operations with Mocked objects.
The implementation for the getAllSettings() looks something like
public Set<Setting> getAllSettings(){
Set<Setting> defaults = getUserSettings();
Set<Setting> custom = getOrganizationSettings();
Set<Setting> undefined = getDefaults();
//perform some sorting and business logic
//return fully sorted set
}
My question lies in how to unit test the getAllSettings() method. Do I use mocks (using easymock/powermock) for all the downstream resource calls that the user/organization/defaultSettings methods use? It seems like there would be a cleaner/better/easier way to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以按照以下形式编写测试,
这将允许您测试获取所有设置的逻辑,独立于其他方法。
另一种选择是模拟这些方法的 IO。如果你有一个执行 IO 逻辑的层,那么它可能会被嘲笑。正如您提到的,如果您有很多依赖项,这可能会很痛苦。也许这表明您需要更少的依赖? (例如,也许班级应该分成更小的单元?)
You could write a test in the following form
This would allow you to test the logic of get all settings, independent of the other methods.
Another alternative would be to mock the IO of these methods. If you have a layer that does the logic of IO, then that could be mocked. As you mention, this can be a pain if you have lots of dependencies. Perhaps a sign that you need less dependencies? (maybe the class should be broken up into smaller units for example?)