Spring Boot GUI Testing Selenium WebDriver

2019-07-17 07:04发布

问题:

I developped a Spring Boot / Angular JS app. Now I'm trying to implement some GUI interface tests.

I tryed to use the Selenium ChromeDriver, so I added the Selenium dependency :

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.4.0</version>
</dependency>

And I created my first test :

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyMainClass.class)
public class SeleniumTest {
    private WebDriver driver;

    @Before
    public void setup() {
        System.setProperty("webdriver.chrome.driver", "my/path/to/chomedriver");
        driver = new ChromeDriver();
    }

    @Test
    public void testTest() throws Exception {
        driver.get("https://www.google.com/");
    }
}

This works fine. But now I want to get my app pages with :

driver.get("http://localhost:8080/");

But I get an "ERR_CONNECTION_REFUSED" in the chrome browser.

I think it's because I need to set up my test to run my web app before to run the test but I don't find how to achieve this ?

回答1:

In your case service is not started. Try something like this this.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SeleniumTest {
    @LocalServerPort
    private int port;
    private WebDriver driver;

    @Value("${server.contextPath}")
    private String contextPath;
    private String base;

    @Before
    public void setUp() throws Exception {
        System.setProperty("webdriver.chrome.driver", "my/path/to/chromedriver");
        driver = new ChromeDriver();
        this.base = "http://localhost:" + port;
    }

    @Test
    public void testTest() throws Exception {
        driver.get(base + contextPath);
    }
}

UPDATE:

Add the dependency

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>