• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.collections.Lists;
7 import org.testng.collections.Maps;
8 import org.testng.xml.XmlSuite;
9 
10 import test.SimpleBaseTest;
11 
12 import java.util.Arrays;
13 import java.util.List;
14 import java.util.Map;
15 
16 /**
17  * Test that classes with dependent methods are still run in different threads
18  * and in the correct order.
19  */
20 public class MultiThreadedDependentTest extends SimpleBaseTest {
21 
22   /**
23    * Make sure that the topological order is preserved and that if
24    * the TestNG runner is configured to run n threads, the dependent
25    * methods are using these n threads.
26    */
assertOrder(List<String> methods)27   private void assertOrder(List<String> methods) {
28     List<String> expectedMethods = Arrays.asList(new String[] {
29       "a1", "a2", "a3", "b1", "b2", "b3", "b4", "b5", "c1", "d", "x", "y", "z", "t"
30     });
31     int size = expectedMethods.size();
32     Assert.assertEquals(methods.size(), size);
33     for (String em : expectedMethods) {
34       Assert.assertTrue(methods.contains(em));
35     }
36     Map<String, Boolean> map = Maps.newHashMap();
37     for (String m : methods) {
38       map.put(m, Boolean.TRUE);
39       if ("b1".equals(m) || "b2".equals(m) || "b3".equals(m) || "b4".equals(m) || "b5".equals(m)) {
40         Assert.assertTrue(map.get("a1"));
41         Assert.assertTrue(map.get("a2"));
42         Assert.assertTrue(map.get("a3"));
43       }
44       if ("d".equals(m)) {
45         Assert.assertTrue(map.get("a1"));
46         Assert.assertTrue(map.get("a2"));
47       }
48       if ("c1".equals(m)) {
49         Assert.assertTrue(map.get("b1"));
50         Assert.assertTrue(map.get("b2"));
51       }
52     }
53     Assert.assertEquals(map.size(), size);
54     for (Boolean val : map.values()) {
55       Assert.assertTrue(val);
56     }
57   }
58 
59   @Test
test2Threads()60   public void test2Threads() {
61     test(2);
62   }
63 
64   @Test
test3Threads()65   public void test3Threads() {
66     test(3);
67   }
68 
test(int threadCount)69   private void test(int threadCount) {
70     Helper.reset();
71     MultiThreadedDependentSampleTest.m_methods = Lists.newArrayList();
72     TestNG tng = create(MultiThreadedDependentSampleTest.class);
73     tng.setThreadCount(threadCount);
74     tng.setParallel(XmlSuite.ParallelMode.METHODS);
75     Map<Long, Long> map = Helper.getMap(MultiThreadedDependentSampleTest.class.getName());
76     synchronized(map) {
77       tng.run();
78       Assert.assertTrue(map.size() > 1, "Map size:" + map.size() + " expected more than 1");
79       assertOrder(MultiThreadedDependentSampleTest.m_methods);
80     }
81   }
82 }
83