Junit is used to write unit tests in springboot, and the test results do not affect the database.
Pom introduces dependencies
If it is a project generated by an IDE, this package has been introduced by default.
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency>
Database original data
Original data
Writing unit test
package com.mos.quote; import com.mos.quote.model.Area; import com.mos.quote.service.IAreaService; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class QuoteApplicationTests { @Autowired private IAreaService areaService; @Test public void contextLoads() { } @Test public void testUpdate(){ Area area = new Area(); area.setCode("001003"); area.setName("洛阳市"); Integer result = areaService.update(area); Assert.assertEquals(1, (long)result); } @Test @Transactional @Rollback public void testUpdate4Rollback(){ Area area = new Area(); area.setCode("001001"); area.setName("郑州市123"); Integer result = areaService.update(area); Assert.assertEquals(1, (long)result); } }
Result Data
Result data
Conclusion
It can be seen that the data of code=001001 has not changed , and the data with code=001003 was modified successfully. Looking back at the code:
@Transactional indicates that the method as a whole is a transaction,
@Rollback indicates that the transaction is rolled back after execution. It supports passing in a parameter value, and the default is true. That is, rollback, false does not rollback.
This annotation also supports annotations on classes. If so, it will be effective for the entire class method.
Annotation on class
The above is the detailed content of What is the role of junit rollback in springboot. For more information, please follow other related articles on the PHP Chinese website!