View Javadoc

1   package com.atlassian.webdriver.testing.simpleserver;
2   
3   import com.atlassian.pageobjects.DefaultProductInstance;
4   import com.atlassian.pageobjects.ProductInstance;
5   import com.atlassian.pageobjects.TestedProduct;
6   import com.atlassian.pageobjects.TestedProductFactory;
7   import com.atlassian.webdriver.testing.runner.ProductContextRunner;
8   import org.junit.runner.notification.RunNotifier;
9   import org.junit.runners.model.InitializationError;
10  import org.junit.runners.model.Statement;
11  
12  /**
13   * Product context runner extension that starts an embedded server before instantiating the product.
14   *
15   * @since 2.1
16   * @see SimpleServer
17   */
18  public class SimpleServerRunner extends ProductContextRunner
19  {
20  
21      private final SimpleServer server = new SimpleServer();
22  
23      /**
24       * Constructor compatible with the underlying default JUnit4 runner.
25       *
26       * @throws org.junit.runners.model.InitializationError
27       *          if the test class is malformed.
28       */
29      public SimpleServerRunner(Class<?> klass) throws InitializationError
30      {
31          super(klass);
32      }
33  
34      @Override
35      protected TestedProduct<?> createProduct(Class<? extends TestedProduct<?>> testedProductClass)
36      {
37          final int port = startServer();
38          return TestedProductFactory.create(testedProductClass, createProductInstance(port), null);
39      }
40  
41      @Override
42      protected Statement classBlock(RunNotifier notifier)
43      {
44          final Statement original = super.classBlock(notifier);
45          return new Statement()
46          {
47              @Override
48              public void evaluate() throws Throwable
49              {
50                  try
51                  {
52                      original.evaluate();
53                  }
54                  finally
55                  {
56                      shutdownServer();
57                  }
58              }
59          };
60      }
61  
62      private int startServer()
63      {
64          try
65          {
66              server.startServer();
67          }
68          catch (Exception e)
69          {
70              throw new RuntimeException(e);
71          }
72          return server.getPort();
73      }
74  
75      private ProductInstance createProductInstance(int port)
76      {
77          return new DefaultProductInstance("http://localhost:" + port, "testapp", port, "/");
78      }
79  
80      private void shutdownServer() throws Exception
81      {
82          server.stopServer();
83      }
84  }