I have 0..n objects, each of which requires a unique identifier, that are created in this way:
public class Squirrel {
private static numSquirrels = 0;
private String id = null;
public Squirrel() {
this(String.valueOf(numSquirrels++);
}
public Squirrel(String id) {
this.id = id;
}
}
This is a problem in a few ways but I’ll give one:
When unit testing, the numSquirrels variable carries over between
tests, even though I may be working with a different population of
squirrels. That means that their IDs continue to increment when I’d
like to start fresh.
- Is this the correct time to use a SquirrelFactory (the ones the kids are raving about)?
- Should I pass the Factory into the Squirrel object using dependency injection, or should the Squirrel class be contained inside the Squirrel Factory which has an interface to the outside world?
- How do I ensure uniqueness if I want the user to be able to set the ID (or at least suggest IDs)?
I think this implementation will work fine, although you should probably use AtomicInteger if you are dealing with concurrency.
Your unit testing problem can be solved using a combination of mocking and wrapping it in another class to mock. See this post
How to mock a static variable in java using JMock
Alternatively, a simple solution would be to expose a setter for the static variable, in which at the end of your test cases, you can set it back to 0, or whatever “reset” means to you.