I have a domain class User:
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'
}
}
}
Where AuditableEntity has only nullable fields.
I also have a simple service class UserService:
@Transactional
class UserService {
@Transactional(readOnly = true)
User getByGoogleId(String googleId) {
def user = User.notDeleted.findByGoogleId(googleId)
user
}
}
I am trying to write a unit test for the service class while mocking User domain:
class UserServiceSpec extends Specification implements ServiceUnitTest<UserService>, DataTest {
def setupSpec() {
mockDomain User
}
void "getByGoogleId"() {
setup:
new User(
username: "username",
googleId: "googleId",
email: "[email protected]",
enabled: true,
accountExpired: false,
accountLocked: false,
passwordExpired: false
).save(failOnError: true)
when:
def user = service.getByGoogleId("googleId")
then:
User.count() == 1
user.username == "username"
}
}
This test fails as it is not creating the user object for some reason. User.count()
is 0.
It is not validation problem, as there are no domain validation errors (they were before).
What am I doing wrong?
Try adding a flush when creating your domain:
...
new User(
username: "username",
googleId: "googleId",
email: "[email protected]",
enabled: true,
accountExpired: false,
accountLocked: false,
passwordExpired: false
).save(failOnError: true, flush: true)
...
I mimicked your setup and this is all that was required.