Assigning static final int in a JUnit (4.8.1) test suite
I have a JUnit test class in which I have several static final int
s that can be redefined at the top of the tester code to allow some variation in the test values. I have logic in my @BeforeClass method to ensure that the developer has entered values that won't break my tests.
I would like to improve variat开发者_C百科ion further by allowing these ints to be set to (sensible) random values in the @BeforeClass method if the developer sets a boolean useRandomValues = true;
. I could simply remove the final
keyword to allow the random values to overwrite the initialisation values, but I have final
there to ensure that these values are not inadvertently changed, as some tests rely on the consistency of these values.
Can I use a constructor in a JUnit test class? Eclipse starts putting red underlines everywhere if I try to make my @BeforeClass into a constructor for the test class, and making a separate constructor doesn't seem to allow assignment to these variables (even if I leave them unassigned at their declaration);
Is there another way to ensure that any attempt to change these variables after the @BeforeClass method will result in a compile-time error?
Can I make something final after it has been initialised?
You can do this with a static constructor:
import java.util.Random;
public class StaticRandom
{
private static final boolean useRandomValues = true;
private static final Random r = new Random();
private static final int value1;
private static final int value2;
private static final int value3;
static
{
if(useRandomValues)
{
value1 = r.nextInt();
value2 = r.nextInt();
value3 = r.nextInt();
}
else
{
value1 = 0;
value2 = 0;
value3 = 0;
}
}
}
You can use a static initializer:
final static boolean useRandomValues = true;
final static int valueA;
final static int valueB;
static {
if(!useRandomValues) {
valueA = 42;
valueB = 1337;
}
else {
Random rnd = new Random();
valueA = rnd.nextInt(100);
valueB = rnd.nextInt(100);
}
}
精彩评论