带有批注的Spring硒测试

这篇文章描述了如何在Java中实现Selenium测试。 它的灵感来自Alex Collins的帖子,并带有注释。 该代码可在GitHub的Spring-Selenium-Test目录中找到。 一些替代方法和更轻巧的技术可用于对Spring MVC应用程序进行单元测试。 要进行单元测试服务,请参见此处

页面,配置和控制器

我们使用“ Hello World”创建一个简单页面:

<!doctype html>
<html lang='en'>
<head>
  <meta charset='utf-8'>
  <title>Welcome !!!</title>
</head>
<body>
  <h1>
   Hello World !
  </h1>
</body>
</html>

我们使控制器非常简单:

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = 'com.jverstry')
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix('WEB-INF/pages/');
        resolver.setSuffix('.jsp');
        return resolver;
    }

}

还有我们的控制器:

@Controller
public class MyController {

    @RequestMapping(value = '/')
    public String home() {
        return 'index';
    }

}

用于硒测试

我们创建一个测试配置。 它提供了在本地打开应用程序的URL。 该应用程序是使用Firefox打开的:

@Configuration
public class TestConfig {

    @Bean
    public URI getSiteBase() throws URISyntaxException {
        return new URI('http://localhost:10001/spring-selenium-test-1.0.0');
    }

    @Bean(destroyMethod='quit')
    public FirefoxDriver getDrv() {
        return new FirefoxDriver();
    }

}

我们还定义了一个抽象类作为所有测试的基础。 测试后,它将自动关闭Firefox:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={ TestConfig.class })
public abstract class AbstractTestIT {

    @Autowired
    protected URI siteBase;

    @Autowired
    protected WebDriver drv;

    {
        Runtime.getRuntime().addShutdownHook(new Thread() {
           @Override
           public void run() {
                drv.close();
           }
        });
    }

}

然后我们执行硒测试,以确保我们的页面包含“ Hello World”:

public class SeleniumTestIT extends AbstractTestIT {

    @Test
    public void testWeSeeHelloWorld() {
        drv.get(siteBase.toString());
        assertTrue(drv.getPageSource().contains('Hello World'));
    }

}

Maven依赖项与Alex Collins帖子中描述的依赖项相同。

构建应用程序

如果您构建了该应用程序,它将自动打开和关闭firefox。 测试将成功。

参考: 技术说明博客上的JCG合作伙伴 Jerome Versrynge提供的带注释的Spring硒测试

翻译自: https://www.javacodegeeks.com/2013/01/spring-selenium-tests-with-annotations.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值