单元测试:测试类所需所有东西//无法调用数据库(一直失败报空指针或者fail to load application)

普通的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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值