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

内容简介

  • 什么事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     }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值