简体   繁体   中英

Why @Transactional and @Rollback don't work?

I'm using Spring boot with Kotlin and database which I use is PostgreSQL. When I wrote the test, I found that @Rollback does not working.

application-test.properties

# Database configuration
spring.datasource.url=jdbc:postgresql://localhost:5432/magnus
spring.datasource.username=postgres
spring.datasource.password=123456
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.database=POSTGRESQL

IUserInfoRepository.java

interface IUserInfoRepository : JpaRepository<UserInfo, UUID> {
    fun findByUserName(name: String): UserInfo?

    @Transactional
    fun deleteByUserName(name: String): Int
}

UserService.java

@Service
class UserService(@Autowired val userInfoRepository: IUserInfoRepository) {
    private lateinit var user: User
    fun initService(user: User) {
        this.user = user;
    }

    fun createUser(userName: String, password: ByteArray, nickName: String, isAdmin: Boolean): Boolean {
        if (userInfoRepository.findByUserName(userName) != null) {
            return false
        }
        val hashCodeTable = HashCodeTable(RandomStringUtils.randomAscii(16).toByteArray())
        val hashedPassword = genHashedPassword(password, hashCodeTable.salt1)
        userInfoRepository.save(UserInfo(userName, nickName, hashedPassword, hashCodeTable, isAdmin))
        return true
    }


    fun deleteUser(): Boolean {
        return validateUserAndDo {
            userInfoRepository.deleteByUserName(user.userName)
            true
        }
    }

    fun findUser(): UserInfo? {
        return userInfoRepository.findByUserName(user.userName)
    }

    fun validateUser(): Boolean {
        return (findUser()?.hashedPassword?.contentEquals(user.password)) ?: false
    }

    fun getLoginSalt(userName: String): ByteArray {
        return userInfoRepository.findByUserName(userName)?.hashCodeTable?.salt1 ?: ByteArray(0)
    }

    fun changePassword(newPassword: ByteArray): Boolean {
        return validateUserAndDo() {
            val oldUser = findUser()!!
            val hashedPassword = genHashedPassword(newPassword, oldUser.hashCodeTable.salt1)
            val newUser = UserInfo(oldUser.userName, oldUser.nickName, hashedPassword, oldUser.hashCodeTable, oldUser.isAdmin, oldUser.subscriptionTable, oldUser.id, oldUser.categoryTables)
            userInfoRepository.save(newUser)
            true
        }
    }

    private fun validateUserAndDo(something: () -> Boolean): Boolean {
        if (validateUser()) {
            return something.invoke()
        }
        return false
    }

    fun changeNickName(newNickName: String): Boolean {
        return validateUserAndDo() {
            val oldUser = findUser()!!
            val newUser = UserInfo(oldUser.userName, newNickName, oldUser.hashedPassword, oldUser.hashCodeTable, oldUser.isAdmin, oldUser.subscriptionTable, oldUser.id, oldUser.categoryTables)
            userInfoRepository.save(newUser)
            true
        }
    }

    fun changePermission(isAdmin: Boolean): Boolean {
        return validateUserAndDo() {
            val oldUser = findUser()!!
            val newUser = UserInfo(oldUser.userName, oldUser.nickName, oldUser.hashedPassword, oldUser.hashCodeTable, isAdmin, oldUser.subscriptionTable, oldUser.id, oldUser.categoryTables)
            userInfoRepository.save(newUser)
            true
        }
    }

    fun isPermission(): Boolean {
        return userInfoRepository.findByUserName(user.userName)?.isAdmin ?: false
    }

    fun deleteAll(): Boolean {
        userInfoRepository.deleteAll()
        return true
    }
}

UserServiceTest.java

@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class UserServiceTest(@Autowired val userService: UserService) {
    private lateinit var userName: String
    private lateinit var password: ByteArray

    @BeforeAll
    fun beforeTest() {
        userName = "test"
        password = "123456".toByteArray()
        userService.createUser(userName, password, "Test", false)
        val user = User(userName, genHashedPassword(password, userService.getLoginSalt(userName)))
        userService.initService(user);
    }

    @Test
    @Rollback
    fun `delete user`() {
        userService.deleteUser()
        Assertions.assertNull(userService.findUser())
    }

    @Test
    @Rollback
    fun `get login salt`() {
        Assertions.assertEquals(userService.getLoginSalt(userName).contentEquals(ByteArray(0)), false)
    }

    @Test
    @Rollback
    fun `validate User`() {
        Assertions.assertEquals(userService.validateUser(), true)
    }
}

With regards @Transactional, the Spring Documentation states :

Annotating a test method with @Transactional causes the test to be run within a transaction that will, by default, be automatically rolled back after completion of the test. If a test class is annotated with @Transactional, each test method within that class hierarchy will be run within a transaction. Test methods that are not annotated with @Transactional (at the class or method level) will not be run within a transaction.

With regards the @Rollback Annotation, the Spring Documentation states:

Indicates whether the transaction for a transactional test method should be rolled back after the test method has completed. If true, the transaction is rolled back; otherwise, the transaction is committed (see also @Commit). Rollback semantics for integration tests in the Spring TestContext Framework default to true even if @Rollback is not explicitly declared.

When declared as a class-level annotation, @Rollback defines the default rollback semantics for all test methods within the test class hierarchy. When declared as a method-level annotation, @Rollback defines rollback semantics for the specific test method, potentially overriding class-level @Rollback or @Commit semantics.

Please Refer To : https://docs.spring.io/spring/docs/4.2.5.RELEASE/spring-framework-reference/html/integration-testing.html#testcontext-tx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM