原因:
一、在pom.xml中添加依赖
添加此依赖,注意版本号要和spring-context的版本号相同
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
添加junit依赖,注意这里一定要是4.12以上版本,不然会出错
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
二、修改测试类
1、在类上面添加注解,注意ContextConfiguration里,要添加classpath:
2、自动注入IAccountService类对象
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private IAccountService as;
@Test
public void testFindAll(){
List<Account> accounts= as.findAllAccount();
for (Account account:accounts){
System.out.println(account);
}
}
@Test
public void testFindById(){
Account account = as.findAccountById(1);
System.out.println(account);
}
@Test
public void testSaveAccount(){
Account account = new Account();
account.setName("小新");
account.setMoney(4000d);
as.saveAccount(account);
System.out.println("插入后如下:");
testFindAll();
}
@Test
public void testUpdateAccount(){
Account account = as.findAccountById(5);
account.setMoney(5000d);
as.updateAccount(account);
System.out.println("更新后如下:");
testFindAll();
}
@Test
public void testDeleteAccount(){
as.deleteAccount(5);
System.out.println("删除后如下:");
testFindAll();
}
}
踩坑记录
之前也是,在添加maven依赖的时候,发现不报红了,但是实际上没有添加进来,即External Libraries下面没有对应的包,右键项目maven->reimport也没有反应,解决办法如下:
1、右键项目—>open Module settings—>左边列表Libraries—>删除错误的包(或者干脆ctrl+a全部删除),此时reimport
2、file—>settings—>Build,Execution,Deployment—>Build Tools—>Maven,勾选Always Update snapshots
3、网上看到的,未实践:删除项目下的imi文件,重启idea