Unit Testing Composite Service Methods
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.
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.
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?)
精彩评论