Creating automatic test suites for your application is a good way to make it robust. It allows you to work in a very agile way.

Play tests are built using JUnit 4 or Selenium depending what you want to test.

Writing tests

The tests must be created in the test/ directory. This folder will only be added to the sources path when the application is run in test mode. You can write 3 different kinds of tests.

Unit test

A unit test is written using JUnit. In this kind of test you can test the model of your application (including some utilities).

Here is an example of a Unit test:

import play.test.*;
import org.junit.*; public class MyTest extends UnitTest { @Test
public void aTest() {
assertEquals(2, 1 + 1); // A really important thing to test
} @Test
public void testUsers() {
assertEquals(3, Users.count());
} }

Functional test

A functional test is written using JUnit. In this kind of test you can test your application by accessing directly the controller objects.

Here is an example of a Functional test:

import play.test.*;
import play.mvc.*;
import play.mvc.Http.*;
import org.junit.*; public class ApplicationTest extends FunctionalTest { @Test
public void testTheHomePage() {
Response response = GET("/");
assertStatus(200, response);
} }

Selenium test

Acceptance tests are written using Selenium. Here you can test your application by running it in an automated browser.

Selenium tests are written using HTML tables. You can either use this native syntax or use the #{selenium /} tag.

Here is an example of a Selenium test:

#{selenium 'Test security'}

    // Try to log in the administration area
clearSession()
open('/admin')
assertTextPresent('Login')
type('login', 'admin')
type('password', 'secret')
clickAndWait('signin') // Verify that the user in correctly logged in
assertText('success', 'Welcom admin!') #{/selenium}

Because Selenium tests are run within your browser access to emails sent by the mock email and to String values placed in the Play Cache must be made using extensions to Selenium.

Here is an example of accessing the most recent email sent to a specific email account:

#{selenium 'Test email sending'}

    // Open email form and send an email to boron@localhost
open('/sendEmail')
assertTextPresent('Email form')
type('To', 'boron@localhost')
type('Subject', 'Berillium Subject')
clickAndWait('send') // Extract the last email sent to boron@localhost into a javascript variable called email
storeLastReceivedEmailBy('boron@localhost', 'email')
// Extract the subject line from the email variable into a variable called subject
store('javascript{/Subject:\s+(.*)/.exec(storedVars["email"])[1]}', 'subject')
// Test the contents of the subject variable
assertEquals('Berillium Subject', '$[subject]') #{/selenium}

Here is an example of accessing a String stored in the Play Cache (for example the correct answer to a CAPTCHA):

#{selenium 'Get string from cache'}

	open('/register')
assertTextPresent('Registration form')
type('Email', 'my@email.com')
type('Password', 'secretpass')
type('Password2', 'secretpass')
// .. Fill in the registration form ..

// Get the value of the magicKey variable from the cache (set to the CAPTCHA answer in the application)
storeCacheEntry(‘magicKey’, ‘captchaAnswer’)
// Type it into the form
type(‘Answer’, ‘$[captchaAnswer]’)

clickAndWait(‘register’)

#{/selenium}

Fixtures

When you run tests, you need to have stable data for your application. The simplest way is to reset your database before each test.

The play.test.Fixtures class helps you to manipulate your database and to inject test data. You typically use it in a @Before method of a JUnit test.

@Before
public void setUp() {
Fixtures.deleteAll();
}

To import data, it is simpler to define them in a YAML file that the Fixtures helper can automatically import.

# Test data

Company(google):
name: Google Company(zen):
name: Zenexity User(guillaume):
name: guillaume
company: zen

And then:

@Before
public void setUp() {
Fixtures.deleteAll();
Fixtures.loadModels("data.yml");
}

You can read more about Play and YAML in the YAML manual page.

For Selenium tests, you can use the #{fixture /} tag:

#{fixture delete:'all', load:'data.yml' /}

#{selenium}

    // Write your test here

#{/selenium}

Sometimes it is convenient to split data into several YAML files. You can load fixtures from multiple files at once:

Fixtures.loadModels("users.yml", "roles.yml", "permissions.yml");

and for Selenium tests:

#{fixture delete:'all', load:['users.yml', 'roles.yml', 'permissions.yml'] /}

Running the tests

To run the tests, you must run your application in test mode using the play test command.

# play test myApp

In this mode, Play will automatically load the test-runner module. This module provides a Web based test runner, available at the http://localhost:9000/@tests URL.

When you run a test, the result is saved into the /test-result directory of your application.

On the test runner page, each test is a link. You can ‘right click’ and ‘Open in a new tab’, to run the test directly outside of the test-runner.

When you run tests this way, Play will start with a special test framework ID. So you can define special configurations in the application.conf file.

If you want several different test-configuration, you can use framework IDs matching the pattern ‘test-?.*’ (e.g: ‘test-special’).
If you use a framework ID other then the default ‘test’, you must make sure ALL test configuration in application.conf is available
with that framework ID. When launching test with special test framework ID you do it like this: 'play test --%test-your-special-id'

For example:

%test.db=mem
%test.jpa.ddl=create-drop

Continuous integration, and running the tests automatically

The auto-test command does the same as the test command, but it automatically launches a browser, runs all the tests, and stops.

This is a useful command if you want to set up a continuous integration system;

After the run, all results are saved to the /test-result directory. Moreover, this directory contains a marker file (either result.failed or result.passed) for the test suite’s final result. Finally, this directory contains all the logs, in an application.log file.

So setting up a continuous integration system to test your application, could be:

  • Checkout the latest version of your application
  • Run play auto-test
  • Wait for the end of the process
  • Check for the marker file result.passed or result.failed in the /test-result directory

Run these steps in a CRON tab, and you’re done!

Continuing the discussion

Next: Security guide.

Test your application的更多相关文章

  1. 玩转Windows服务系列——使用Boost.Application快速构建Windows服务

    玩转Windows服务系列——创建Windows服务一文中,介绍了如何快速使用VS构建一个Windows服务.Debug.Release版本的注册和卸载,及其原理和服务运行.停止流程浅析分别介绍了Wi ...

  2. WCF : 修复 Security settings for this service require Windows Authentication but it is not enabled for the IIS application that hosts this service 问题

    摘要 : 最近遇到了一个奇怪的 WCF 安全配置问题, WCF Service 上面配置了Windows Authentication. IIS上也启用了 Windows Authentication ...

  3. ABP(现代ASP.NET样板开发框架)系列之15、ABP应用层——应用服务(Application services)

    点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之15.ABP应用层——应用服务(Application services) ABP是“ASP.NET Boiler ...

  4. ABP源码分析四十:ZERO的Application和Tenant

    ABP的Zero模块以数据库为数据源实现了ABP框架中的tenant management (multi-tenancy), role management, user management, ses ...

  5. myeclipse 无法启动 java.lang.IllegalStateException: Unable to acquire application service. Ensure that the org.eclipse.core.runtime bundle is resolved and started (see config.ini).

    把myeclipse10 按照目录完整拷贝到了另外一台电脑, 另外的目录 原安装目录 D\:\soft\i\myeclipse10 新安装目录 E\:\soft\myeclipse10 双击启动失败, ...

  6. Android笔记——Application的作用

    一.Application是什么 Application和Actovotu,Service一样是android框架的一个系统组件,当android程序启动时系统会创建一个 application对象, ...

  7. My First Android Application Project 第一个安卓应用

    一.前言: 安卓(Android):是一种基于Linux的自由及开放源代码的操作系统,主要用在移动设备上,如手机.平板电脑.其他的设备也有使用安卓操作系统,比如:电视机,游戏机.数码相机等等. 二.具 ...

  8. 解析大型.NET ERP系统架构设计 Framework+ Application 设计模式

    我对大型系统的理解,从数量上面来讲,源代码超过百万行以上,系统有超过300个以上的功能,从质量上来讲系统应该具备良好的可扩展性和可维护性,系统中的功能紧密关联.除去业务上的复杂性,如何设计这样的一个协 ...

  9. Application Request Route实现IIS Server Farms集群负载详解

    序言 随着公司业务的发展,后台业务就变的越来越多,然而服务器的故障又像月经一样,时不时的汹涌而至,让我们防不胜防.那么后台的高可用,以及服务器的处理能力就要做一个横向扩展的方案,以使后台业务持续的稳定 ...

  10. SharePoint2013 Set a custom application page as site welcome page

    本文主要介绍如何添加一个custom application page as site welcome page 1.首先创建一个sharepoint 2013 empty solution, add ...

随机推荐

  1. 趣谈、浅析CRLF和LF

    作为程序员,在处理文件和输入输出的时候经常要跟CRLF和LF打交道.可能大家多少知道一些,但总是记不清楚,我也是这样的,因此写下这篇博文,作为记录. 首先,明确他们的意思:CR(回车),LF(换行). ...

  2. 关于Ubuntu运行级别、开机启动脚本的说明

    关于Ubuntu运行级别.开机启动脚本的说明 目录简介 1.1介绍Ubuntu下面的自启动脚本目录 1.2 Linux操作系统运行级别的概念 1.3关于操作系统自启脚本的启动顺序 1.4    Lin ...

  3. Github快速入门手册

    最近在试用Github,开源的思想也让人觉得把一些经验分享出来是非常好的事情.附件是doc文件,如有需要请注意查收.希望能对你有帮助. GITHUB基于互联网的版本控制快速入门手册 如有不妥,欢迎指正 ...

  4. Android_TextView之跑马灯效果

    对于android控件中的TextView,相信大家一定不陌生,在显示文本内容时十分方便.不过我在使用时遇到一个小问题,就是当文字交多时,如何为用户进行展示.今天就为大家介绍一种解决方案--跑马灯效果 ...

  5. java中得到classpath和当前类的绝对路径的一些方法(路径中的%20"进行替换空格)

    原网址:http://blog.csdn.net/shendl/article/details/1427475 (注意:利用下面方式得到路径,如果路径中有空格字符, 那么会有"%20&quo ...

  6. python--基础学习(四)自然字符串、重复字符串、子字符串

    python系列均基于python3.4环境 1.自然字符串和重复字符串 代码示例: str1=r'hello \npython' str2='hello \npython' str3="h ...

  7. 推荐一个算法编程学习中文社区-51NOD【算法分级,支持多语言,可在线编译】

    最近偶尔发现一个算法编程学习的论坛,刚开始有点好奇,也只是注册了一下.最近有时间好好研究了一下,的确非常赞,所以推荐给大家.功能和介绍看下面介绍吧.首页的标题很给劲,很纯粹的Coding社区....虽 ...

  8. vs xamarin android 读取rest

    private void Btn_Click(object sender, EventArgs e) { var u = FindViewById<EditText>(Resource.I ...

  9. Gradify - 提取图片颜色,创建响应式的 CSS渐变

    被请求的HTTP对象之间的延迟会有一个时间段,这个期间网页看起来不完整.Gradify 可以分析出图像中4个最常见的颜色,创建一个梯度(或纯色)作为图片占位符.Gradify 可以在在任何图像发现最突 ...

  10. 抓包分析SSL/TLS连接建立过程【总结】

    1.前言 最近在倒腾SSL方面的项目,之前只是虽然对SSL了解过,但是不够深入,正好有机会,认真学习一下.开始了解SSL的是从https开始的,自从百度支持https以后,如今全站https的趋势越来 ...