If you need to check if your testing method takes too long to execute, you can do that by mentioning your expected execution time using timeout property of @Test annotation. If the test execution takes longer than that number of milliseconds it causes a test method to fail.
public class StringConcatenationTest {
private static final int TIMES = 10_000;
// timeout in milliseconds
@Test(timeout = 20)
public void testString(){
String res = "";
for (int i = 0; i < TIMES; i++) {
res += i;
}
System.out.println(res.length());
}
@Test(timeout = 20)
public void testStringBuilder(){
StringBuilder res = new StringBuilder();
for (int i = 0; i < TIMES; i++) {
res.append(i);
}
System.out.println(res.length());
}
@Test(timeout = 20)
public void testStringBuffer(){
StringBuffer res = new StringBufferr();
for (int i = 0; i < TIMES; i++) {
res.append(i);
}
System.out.println(res.length());
}
}
In most cases without JVM warm-up testString
will fail.
But testStringBuffer
and testStringBuilder
should pass this test successfully.