1 package test.thread; 2 3 import org.testng.Assert; 4 import org.testng.TestNG; 5 import org.testng.annotations.Test; 6 import org.testng.xml.XmlSuite; 7 8 import test.SimpleBaseTest; 9 10 import java.util.Arrays; 11 import java.util.List; 12 13 /** 14 * Attempt to make sure that we are truly running methods in parallel. The best I can think 15 * of right now is to run the tests a few times in a row and verify the ordering is never 16 * the same. 17 */ 18 public class TrueParallelTest extends SimpleBaseTest { 19 20 @Test shouldRunInParallel()21 public void shouldRunInParallel() { 22 boolean success = false; 23 for (int i = 0, count = Runtime.getRuntime().availableProcessors() * 4; i < count; i++) { 24 XmlSuite s = createXmlSuite("TrueParallel"); 25 createXmlTest(s, "Test", TrueParallelSampleTest.class.getName()); 26 TestNG tng = create(); 27 s.setParallel(XmlSuite.ParallelMode.METHODS); 28 tng.setXmlSuites(Arrays.asList(s)); 29 BaseThreadTest.initThreadLog(); 30 tng.run(); 31 32 // A sequential result will look like "m1 m1 m3 m3 m2 m2 m4 m4 m5 m5". A properly 33 // multithreaded result will have at least one non-consecutive different pair: 34 // "m1 m1 m3 m2 m4 m4 m2 m3 m5 m5" 35 List<String> strings = TrueParallelSampleTest.getStrings(); 36 boolean ii = isInterleaved(strings); 37 success = success || ii; 38 // System.out.println(strings + " -> " + ii); 39 } 40 Assert.assertTrue(success, "Couldn't find any interleaved test method run"); 41 } 42 isInterleaved(List<String> strings)43 private boolean isInterleaved(List<String> strings) { 44 for (int i = 0; i < strings.size(); i += 2) { 45 if (! strings.get(i).equals(strings.get(i + 1))) { 46 return true; 47 } 48 } 49 return false; 50 } 51 } 52