NEO

蜀道难,难于上青天!

导航

20130515-Grails In Action-3、建模(01小节)

Posted on 2013-05-15 22:36  页面载入出错  阅读(274)  评论(0编辑  收藏  举报

内容简介

  • 什么是GORM,以及GORM怎么工作
  • 定义领域模型
  • 怎么让模型工作,如save、update
  • 验证和约束
  • 领域类的关系(1:1,1:m,m:n)

开始我们的实例程序:hubbub

目标:建立domain对象,增加属性,以及集成测试

1、创建项目

grails create-app hubbub

2、创建第一个domain对象

grails create-domain-class com.grailsinaction.User

3、给User对象添加属性

 1 package com.grailsinaction
 2 
 3 class User {
 4     
 5     String userId
 6     String password
 7     String homepage
 8     Date dateCreated
 9 
10     static constraints = {
11     }
12 }

 4、对User对象进行集成测试

grails create-integration-test com.grailsinaction.UserIntegration

5、增加测试代码

 1 package com.grailsinaction
 2 
 3 import static org.junit.Assert.*
 4 import org.junit.*
 5 
 6 class UserIntegrationTests {
 7 
 8     @Before
 9     void setUp() {
10         // Setup logic here
11     }
12 
13     @After
14     void tearDown() {
15         // Tear down logic here
16     }
17 
18     @Test
19     void testFirstSaveEver() {
20         def user = new User(userId: 'joe', password: 'secret', homepage: 'http://www.grailsinaction.com')
21         assertNotNull user.save()
22         assertNotNull user.id
23         def foundUser = User.get(user.id)
24         assertEquals 'joe', foundUser.userId
25     }
26 }

6、运行集成测试

grails test-app -integration

7、测试结果

| Running 1 integration test... 1 of 1
| Completed 1 integration test, 0 failed in 2218ms
| Tests PASSED - view reports in E:\example\grails\hubbub_03\target\test-reports

8、User对象保存和更新测试

在com.grailsinaction.UserIntegration中增加测试代码

 1     @Test
 2     void testSaveAndUpdate() {
 3         def user = new User(userId: 'joe', password: 'secret', homepage: 'http://www.grailsinaction.com')
 4         assertNotNull user.save()
 5         def foundUser = User.get(user.id)
 6         foundUser.password = 'sesame'
 7         foundUser.save()
 8         def editedUser = User.get(user.id)
 9         assertEquals 'sesame', editedUser.password
10     }

9、再运行、查看测试结果

| Running 2 integration tests... 1 of 2
| Running 2 integration tests... 2 of 2
| Completed 2 integration tests, 0 failed in 2562ms
| Tests PASSED - view reports in E:\example\grails\hubbub_03\target\test-reports

10、User对象保存、删除测试

1     @Test
2     void testSaveThenDelete() {
3         def user = new User(userId: 'joe', password: 'secret', homepage: 'http://www.grailsinaction.com')
4         assertNotNull user.save()
5         def foundUser = User.get(user.id)
6         foundUser.delete()
7         assertFalse User.exists(foundUser.id)
8     }