Skip to content

Instantly share code, notes, and snippets.

@bhavanki
Created March 20, 2014 15:32
Show Gist options
  • Save bhavanki/9666471 to your computer and use it in GitHub Desktop.
Save bhavanki/9666471 to your computer and use it in GitHub Desktop.
An example of using a factory class to improve testability over a static method call.
/*
* Current getMetadataTable() method. This is hard to test because it requires a real HdfsZooInstance object.
*/
public synchronized static Writer getMetadataTable(Credentials credentials) {
Writer metadataTable = metadata_tables.get(credentials);
if (metadataTable == null) {
metadataTable = new Writer(HdfsZooInstance.getInstance(), credentials, MetadataTable.ID);
metadata_tables.put(credentials, metadataTable);
}
return metadataTable;
}
/*
* A more testable getMetadataTable() method using an instance factory.
*/
private static InstanceFactory ifactory = new HdfsZooInstanceFactory(); // default for production
static InstanceFactory getInstanceFactory() {
return ifactory;
}
static void setInstanceFactory(InstanceFactory ifactory) {
MetadataTableUtil.ifactory = ifactory;
}
public synchronized static Writer getMetadataTable(Credentials credentials) {
Writer metadataTable = metadata_tables.get(credentials);
if (metadataTable == null) {
// now the factory provides the instance instead of a static method call
metadataTable = new Writer(ifactory.getInstance(), credentials, MetadataTable.ID);
metadata_tables.put(credentials, metadataTable);
}
return metadataTable;
}
/*
* Test code for the method.
*/
@BeforeClass public static void setUpClass() {
// replace the instance factory in the class under test with one that returns a mock instance
priorInstanceFactory = MetadataTableUtil.getInstanceFactory();
mockInstanceFactory = new MockInstanceFactory();
MetadataTableUtil.setInstanceFactory(mockInstanceFactory);
}
@AfterClass public static void tearDownClass() {
// clean up: put back the "real" instance factory
MetadataTableUtil.setInstanceFactory(priorInstanceFactory);
}
@Before public void setUp() {
// create a mock instance and put it in place to be returned by the factory
instance = createMock(Instance.class);
mockInstanceFactory.setInstance(instance);
// now I can tell the mock instance to behave in ways I need it to
expect(instance.getInstanceID()).andReturn(INSTANCE_ID);
replay(instance);
}
@Test public void testGetMetadataTable() {
Credentials credentials = createMock(Credentials.class);
Writer writer = MetadataTableUtil.getMetadataTable(credentials);
// assertions about returned writer go here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment