In Java why this error: 'attribute value must be constant'?

djangofan picture djangofan · Jan 19, 2015 · Viewed 35k times · Source

I have some TestNG code, where I am passing a Test annotation parameter called timeOut = TESTNG_TEST_TIMEOUT .

@Test(description = "Tests something.", groups = { "regression" }, 
   timeOut = TESTNG_TEST_TIMEOUT, enabled = true)

And in my TestBase class I have this member:

public final static long TESTNG_TEST_TIMEOUT = TimeUnit.MINUTES.toMillis(5);

When I use the above line of code, I get a 'attribute value must be constant' error in Eclipse.

But, if I simply define the member like so, it works:

public final static long TESTNG_TEST_TIMEOUT = 300000;

Is the use of TimeUnit not a constant?

Answer

Sotirios Delimanolis picture Sotirios Delimanolis · Jan 19, 2015

This

public final static long TESTNG_TEST_TIMEOUT = 300000;

is a constant variable, a type of constant expression.

This

public final static long TESTNG_TEST_TIMEOUT = TimeUnit.MINUTES.toMillis(5);

is not.

Annotation members expect constant expressions (and a few other things like enums and Class literals).