普通的Spring项目:
要在测试类的头顶加上
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-context.xml"})
加载spring配置
SpringBoot项目:
1、在src下,与main包同级新建test包,并将其标记为Test Resources Root
2、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
3、在自己编写的测试类的头顶加上
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
// 事务回滚
@TransactionalRollbackAll
4、这里的注解是重写了的,代码如下:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.transaction.annotation.Transactional;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Transactional(rollbackFor = Throwable.class)
public @interface TransactionalRollbackAll {
}
这个是以前写的了,现在淘汰这个注解的写法
@TransactionConfiguration:defaultRollback默认值为true,设了这个就代表事务自动回滚,就是不管你怎么操作数据库,数据库都会变成原来的样子
// 事务回滚
@TransactionConfiguration