对应工程heima-annoioc-withoutxml
上文提到说junit存在着大量重复代码,如下进行修改:
public class AccountServiceTest {
private ApplicationContext ac = null;
private IAccountService as = null;
public void init() {
// 1.获取容器,此时采用被注解过的类
ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
// 2.获取业务层对象
as = ac.getBean("accountService", IAccountService.class);
}
public void testFindAll() {
// 3.执行方法
List<Account> allaccounts = as.findAllAccount();
for (Account aaa : allaccounts) {
System.out.println(aaa);
}
}
public void testFindOne() {
// 3.执行方法
Account oneaccount = as.findAccountById(1);
System.out.println(oneaccount);
}
public void testSave() {
// 出现报错说id没有默认值,那就在数据库里面把id弄成自增
Account saveaccount = new Account();
saveaccount.setName("水野朝阳");
saveaccount.setMoney(1000f);
// 3.执行方法
as.saveAccount(saveaccount);
}
public void testUpdate() {
// 3.执行方法
Account updateaccount = as.findAccountById(2);
updateaccount.setMoney(1000f);
as.updateAccount(updateaccount);
}
public void testDelete() {
// 3.执行方法
as.deleteAccount(6);
}
}
还有一种方法就是采用Spring整合junit的配置:
- 导入spring整合Junit的jar
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
- 使用Junit提供的一个注解把原有的main方法替换了,换成spring提供的@Runwith。例子如下:
SpringJUnit4ClassRunner.class)(
public class AccountServiceTest {}
- 告知spring的运行器,spring和ioc创建的基于xml还是注解的,并说明位置。
@ContextConfiguration 属性:
locations : 指定xml位置,加上classpath关键字,表示在类路径下
classes: 指定配置类所在位置
例子如下:
SpringJUnit4ClassRunner.class)(
(classes = SpringConfiguration.class)
public class AccountServiceTest {}
总结:当使用spring 5.X版本的时候,要求junit的jar必须是4.12以上。
整体代码如下:
SpringJUnit4ClassRunner.class)(
(classes = SpringConfiguration.class)
public class AccountServiceTest {
private IAccountService as = null;
public void testFindAll() {
// 3.执行方法
List<Account> allaccounts = as.findAllAccount();
for (Account aaa : allaccounts) {
System.out.println(aaa);
}
}
public void testFindOne() {
// 3.执行方法
Account oneaccount = as.findAccountById(1);
System.out.println(oneaccount);
}
public void testSave() {
// 出现报错说id没有默认值,那就在数据库里面把id弄成自增
Account saveaccount = new Account();
saveaccount.setName("水野朝阳");
saveaccount.setMoney(1000f);
// 3.执行方法
as.saveAccount(saveaccount);
}
public void testUpdate() {
// 3.执行方法
Account updateaccount = as.findAccountById(2);
updateaccount.setMoney(1000f);
as.updateAccount(updateaccount);
}
public void testDelete() {
// 3.执行方法
as.deleteAccount(6);
}
}