1
+ import com .example .DemoApplication ;
1
2
import org .junit .Rule ;
2
3
import org .junit .Test ;
4
+ import org .junit .runner .RunWith ;
3
5
import org .openqa .selenium .WebElement ;
4
- import org .openqa .selenium .remote .RemoteWebDriver ;
5
6
import org .openqa .selenium .chrome .ChromeOptions ;
7
+ import org .openqa .selenium .remote .RemoteWebDriver ;
8
+ import org .springframework .boot .test .context .SpringBootTest ;
9
+ import org .springframework .boot .web .context .WebServerInitializedEvent ;
10
+ import org .springframework .boot .web .server .LocalServerPort ;
11
+ import org .springframework .context .ApplicationContextInitializer ;
12
+ import org .springframework .context .ApplicationListener ;
13
+ import org .springframework .context .ConfigurableApplicationContext ;
14
+ import org .springframework .test .context .ContextConfiguration ;
15
+ import org .springframework .test .context .junit4 .SpringJUnit4ClassRunner ;
16
+ import org .testcontainers .Testcontainers ;
6
17
import org .testcontainers .containers .BrowserWebDriverContainer ;
7
18
8
19
import java .io .File ;
14
25
/**
15
26
* Simple example of plain Selenium usage.
16
27
*/
28
+ @ RunWith (SpringJUnit4ClassRunner .class )
29
+ @ SpringBootTest (classes = DemoApplication .class , webEnvironment = SpringBootTest .WebEnvironment .RANDOM_PORT )
30
+ @ ContextConfiguration (initializers = SeleniumContainerTest .Initializer .class )
17
31
public class SeleniumContainerTest {
18
32
33
+ @ LocalServerPort
34
+ private int port ;
35
+
19
36
@ Rule
20
37
public BrowserWebDriverContainer chrome = new BrowserWebDriverContainer ()
21
38
.withCapabilities (new ChromeOptions ())
@@ -25,9 +42,19 @@ public class SeleniumContainerTest {
25
42
public void simplePlainSeleniumTest () {
26
43
RemoteWebDriver driver = chrome .getWebDriver ();
27
44
28
- driver .get ("https ://wikipedia.org " );
29
- List <WebElement > searchInput = driver .findElementsByName ( "search " );
45
+ driver .get ("http ://host.testcontainers.internal:" + port + "/foo.html " );
46
+ List <WebElement > hElement = driver .findElementsByTagName ( "h " );
30
47
31
- assertTrue ("The search input box is found" , searchInput != null && searchInput .size () > 0 );
48
+ assertTrue ("The h element is found" , hElement != null && hElement .size () > 0 );
32
49
}
50
+
51
+ public static class Initializer implements ApplicationContextInitializer <ConfigurableApplicationContext > {
52
+ @ Override
53
+ public void initialize (ConfigurableApplicationContext applicationContext ) {
54
+ applicationContext .addApplicationListener ((ApplicationListener <WebServerInitializedEvent >) event -> {
55
+ Testcontainers .exposeHostPorts (event .getWebServer ().getPort ());
56
+ });
57
+ }
58
+ }
59
+
33
60
}
0 commit comments