欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Play Framework介绍:Hello World(1)(3)

来源: javaer 分享于  点击 9125 次 点评:178

自定义布局

可以修改模板更改布局。编辑helloworld/app/views/main.html文件:

image

添加验证

给form添加一个验证,要求name字段必填。我们通过Play validation实现。编辑helloworld/app/controllers/Application.java,在sayHello action处:

  1. public static void sayHello(@Required String myName) {  
  2.         if (validation.hasErrors()) {  
  3.             flash.error("Oops, please enter your name!");  
  4.             index();  
  5.         }  
  6.         render(myName);  
  7.     } 

并import play.data.validation.*。@Required告诉Play自动检查myName字段是否填写。如果验证失败,我们加入一条消息到flash scope中并重定向到index动作。flash scope允许在重定向时保持消息。

编辑helloworld/app/views/Application/index.html显示错误消息

  1. #{extends 'main.html' /}  
  2. #{set title:'Home' /}  
  3.    
  4. #{if flash.error}  
  5.     <p style="color:#c00">  
  6.         ${flash.error}  
  7.     </p>  
  8. #{/if}  
  9.  
  10. <form action="@{Application.sayHello()}" method="GET">  
  11.     <input type="text" name="myName" />   
  12.     <input type="submit" value="Say hello!" />  
  13. </form> 

输入空参数并提交,OK起作用了。

image

自动化测试

Selenium Test

在测试模式下运行应用。在cmd中输入play test helloworld。

image

打开浏览器,输入http://localhost:9000/@tests启动测试器。

image

执行测试

image

Selenium测试用例通常写成一个html文件。Play使用Play模板引擎生成这些文件。helloworld/test/Application.test.html文件:

  1. *{ You can use plain selenium command using the selenium tag }*  
  2.  
  3. #{selenium}  
  4.     // Open the home page, and check that no error occured  
  5.     open('/')  
  6.     assertNotTitle('Application error')  
  7. #{/selenium} 

此测试打开home页,确认响应中没有“Application error”。

让我们来编写自己的测试。编辑测试内容:

  1. *{ You can use plain selenium command using the selenium tag }*  
  2.  
  3. #{selenium}  
  4.     // Open the home page, and check that no error occurred  
  5.     open('/')  
  6.     assertNotTitle('Application error')  
  7.       
  8.     // Check that it is the form  
  9.     assertTextPresent('The Hello world app.')  
  10.       
  11.     // Submit the form  
  12.     clickAndWait('css=input[type=submit]')  
  13.       
  14.     // Check the error  
  15.     assertTextPresent('Oops, please enter your name!')  
  16.       
  17.     // Type the name and submit  
  18.     type('css=input[type=text]''bob')  
  19.     clickAndWait('css=input[type=submit]')  
  20.       
  21.     // Check the result  
  22.     assertTextPresent('Hello bob!')  
  23.     assertTextPresent('The Hello world app.')  
  24.       
  25.     // Check the back link  
  26.     clickAndWait('link=Back to form')  
  27.       
  28.     // Home page?  
  29.     assertTextNotPresent('Hello bob!')  
  30. #{/selenium} 

重新执行

image

 


相关栏目:

用户点评