Skip to content

Instantly share code, notes, and snippets.

@npathai
Last active August 29, 2015 14:10
Show Gist options
  • Save npathai/71a2e9cdc9ef89220d7f to your computer and use it in GitHub Desktop.
Save npathai/71a2e9cdc9ef89220d7f to your computer and use it in GitHub Desktop.
Unit testing a class dependent on System clock
/*
* This is a mockup of JLine2 library structure. I am working on a feature that provides timestamp
* and wanted to test it and hence this gist. The question that I asking via this gist is that how
* should I test MemoryHistory?
*/
/**
* Represents the history of commands a user has given to a system via any interface such as
* Command Line
*/
public interface History {
void add(String command);
}
/**
* A in memory history that keeps the history in memory and does not preserve history
*/
class MemoryHistory implements History {
private List<String> commands;
private List<long> timestamps;
@Override
public add(String command) {
commands.add(command);
timestamps.add(System.currentTimeMillis()); // here is the dependency on system time
}
}
/**
* Possible approach 1: Create a default constructor that takes a TimeSource interface as an
* argument and use that as a source of timestamp
*/
interface TimeSource {
long currentTimeMillis();
}
/*
* Adding a constructor with package visibility to accept a parameter, TimeSource
*/
class MemoryHistory implements History {
MemoryHistory(TimeSource timesource) {
// now I can unit test the code with predictable values
}
}
/*
* So the question is should I create an extra indirection for unit testing something dependent
* on time? Does that spoil the design? I viewed the "Is TDD Dead?" series and have started to
* think a bit more on Test induced damage. So I was wondering whether this damages the design
* or is there a better approach to do this?
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment