我有一个域类用户:
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'
}
}
}
AuditableEntity只有可以为空的字段。
我还有一个简单的服务类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。
这不是验证问题,因为没有域验证错误(它们之前是)。
我做错了什么?
答案 0 :(得分:0)
尝试在创建域时添加刷新:
...
new User(
username: "username",
googleId: "googleId",
email: "user@domain.com",
enabled: true,
accountExpired: false,
accountLocked: false,
passwordExpired: false
).save(failOnError: true, flush: true)
...
我模仿了你的设置,这就是所需要的。