https://www.bilibili.com/video/av47952931
p44~45
用于解决之前测试时的重复代码
原本的AccountServiceTest中,每个方法中都有步骤1和2
public class AccountServiceTest {
@Test
public void testCreate(){
// 1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
// 2.得到业务层对象
IAccountService as = ac.getBean("accountService",IAccountService.class);
// 3.执行方法
Account account = new Account();
account.setName("eee");
account.setMoney(10000f);
as.createAccount(account);
}
@Test
public void testDelete(){
// 1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
// 2.得到业务层对象
IAccountService as = ac.getBean("accountService",IAccountService.class);
// 3.执行方法
as.deleteAccount(1);
}
}
使用init()可以将重复代码抽出来
public class AccountServiceTest {
private ApplicationContext ac;
private IAccountService as;
@Before
public void init(){
// 1.获取容器
ac = new ClassPathXmlApplicationContext("beans.xml");
// 2.得到业务层对象
as = ac.getBean("accountService",IAccountService.class);
}
@Test
public void testCreate(){
Account account = new Account();
account.setName("eee");
account.setMoney(10000f);
as.createAccount(account);
}
@Test
public void testDelete(){
as.deleteAccount(1);
}
}
但是并没有根本上解决问题
开发和测试的代码仍在一个类中,需要进一步解耦
如果不要init(),只在变量上加@Autowired没有用
一波分析:
解决方法:
- pom.xml中导入spring整合junit的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
且:使用spring 5.x时,juint需要4.12以上的版本
-
使用junit的@RunWith注解将原有的main()替换成spring提供的
-
用@ContextConfiguration告知spring的运行器,基于xml还是注解,并说明位置
locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
classes:指定注释类所在的位置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:beans.xml")
public class AccountServiceTest {
@Autowired
private IAccountService as;
@Test
public void testCreate(){
Account account = new Account();
account.setName("eee");
account.setMoney(10000f);
as.createAccount(account);
}
}
即可正常执行