在Grails中编写超级简单的测试的问题



我有一个域类 用户:

class User extends AuditableEntity {
private static final long serialVersionUID = 1
String username
String password
String email
String googleId
String linkedinId
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
Set<Role> getAuthorities() {
(UserRole.findAllByUser(this) as List<UserRole>)*.role as Set<Role>
}
static constraints = {
password nullable: true, blank: true, password: true
username nullable: false, blank: false, unique: true
email nullable: false, blank: false, unique: true
googleId nullable: true, blank: true, unique: true
linkedinId nullable: true, blank: true, unique: true
}
static mapping = {
password column: '`password`'
googleId column: 'google_id'
linkedinId column: 'linkedin_id'
}
static namedQueries = {
notDeleted {
isNull 'deletedAt'
}
}
}

其中,可审计实体只有可为空的字段。

我也有一个简单的服务类UserService:

@Transactional
class UserService {
@Transactional(readOnly = true)
User getByGoogleId(String googleId) {
def user = User.notDeleted.findByGoogleId(googleId)
user
}
}

我正在尝试在模拟用户域时为服务类编写单元测试:

class UserServiceSpec extends Specification implements ServiceUnitTest<UserService>, DataTest {
def setupSpec() {
mockDomain User
}
void "getByGoogleId"() {
setup:
new User(
username: "username",
googleId: "googleId",
email: "user@domain.com",
enabled: true,
accountExpired: false,
accountLocked: false,
passwordExpired: false
).save(failOnError: true)
when:
def user = service.getByGoogleId("googleId")
then:
User.count() == 1
user.username == "username"
}
}

此测试失败,因为它由于某种原因未创建用户对象。User.count()为 0。 这不是验证问题,因为没有域验证错误(以前是(。

我做错了什么?

尝试在创建域时添加刷新:

...
new User(
username: "username",
googleId: "googleId",
email: "user@domain.com",
enabled: true,
accountExpired: false,
accountLocked: false,
passwordExpired: false
).save(failOnError: true, flush: true)
...

我模仿了您的设置,这就是所需要的。

最新更新