您的位置:首页 > 大数据 > 人工智能

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

2013-05-17 19:32 218 查看

内容简介

什么事GORM,以及GORM怎么工作

定义领域模型

怎么让模型工作,如save、update

验证和约束

领域类的关系(1:1,1:m,m:n)

建立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     }


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: