单元测试组合服务方法 [英] Unit Testing Composite Service Methods

查看:92
本文介绍了单元测试组合服务方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个类编写(junit)单元测试,该类使用以下方法实现暴露的接口:

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();

从特定层获取设置的方法在各个地方进行IO,以获取其结果. 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.

我已经为getUserSettings(),getOrganizationSettings(),getDefaults()编写了单元测试,并模拟了模拟对象的IO操作.

I've already written the unit tests for getUserSettings(), getOrganizationSettings(), getDefaults(), mocking out the IO operations with Mocked objects.

getAllSettings()的实现类似于

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

}

我的问题在于如何对getAllSettings()方法进行单元测试.我是否对用户/组织/defaultSettings方法使用的所有下游资源调用使用模拟(使用easymock/powermock)?似乎会有一种更清洁/更好/更简便的方法.

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.

推荐答案

您可以按照以下形式编写测试

You could write a test in the following form

@Test
public void testGetAllSettings() {
   Foo fixture = new Foo() {
       public Set<Setting> getUserSettings() { // canned impl }
       public Set<Setting> getOrganizationSettings() { // canned impl }
       public Set<Setting> getDefaults() { // canned impl }
   }

   Assert.assertEquals(whatEverItShouldEqual, fixture.getAllSettings());
}

这将使您能够测试获取所有设置的逻辑,而与其他方法无关.

This would allow you to test the logic of get all settings, independent of the other methods.

另一种选择是模拟这些方法的IO.如果您具有执行IO逻辑的层,则可以嘲笑该层.如您所述,如果您有很多依赖关系,这可能会很痛苦.也许有迹象表明您需要更少的依赖关系? (例如,也许应该将班级分解为较小的单元?)

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?)

这篇关于单元测试组合服务方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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