Skip to content

Instantly share code, notes, and snippets.

@coderunner
Created August 22, 2011 02:24
Show Gist options
  • Select an option

  • Save coderunner/1161530 to your computer and use it in GitHub Desktop.

Select an option

Save coderunner/1161530 to your computer and use it in GitHub Desktop.
nondeterministic
public class CurrentTimeFormatter
{
private static String FORMAT = "Current time in millis is : ";
//Not testable since can not predict value of
//System.currentTimeMillis()
public String formatCurrentTime_notTestable()
{
return FORMAT + System.currentTimeMillis();
}
//Can mock TimeAccessor in test code.
public String formatCurrentTime(TimeAccessor aTimeAccessor)
{
return FORMAT + aTimeAccessor.getCurrentTime();
}
//Can override getCurrentTime in test code.
public String formatCurrentTime()
{
return FORMAT + getCurrentTime();
}
long getCurrentTime()
{
return System.currentTimeMillis();
}
}
/*** test code ***/
public class TestCurrentTimeFormatter
{
private static final long CURRENT_TIME = 1000l;
@Test
public void testWithTestObject()
{
//Use mock or test object
//Here a test object is used since we don't care if a call to time
//accessor is made as long as the output string is all right.
TimeAccessor accessor =
TestObject.createTestObject(TimeAccessor.class);
TestObject.Recorder<TimeAccessor> accessorRecorder =
new TestObject.Recorder<TimeAccessor>(accessor);
accessorRecorder.record(accessor.getCurrentTime())
.andReturn(CURRENT_TIME);
CurrentTimeFormatter formatter = new CurrentTimeFormatter();
assertEquals("Current time in millis is : " + CURRENT_TIME,
formatter.formatCurrentTime(accessor));
}
@Test
public void testWithPackagePrivateMethod()
{
//override non deterministic call
CurrentTimeFormatter formatter = new CurrentTimeFormatter()
{
long getCurrentTime()
{
return CURRENT_TIME;
}
};
assertEquals("Current time in millis is : " + CURRENT_TIME,
formatter.formatCurrentTime());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment