https://www.bilibili.com/video/av47952931 p44~45
用于解决之前测试时的重复代码
原本的AccountServiceTest中,每个方法中都有步骤1和2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class AccountServiceTest { @Test public void testCreate () { ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml" ); IAccountService as = ac.getBean("accountService" ,IAccountService.class); Account account = new Account(); account.setName("eee" ); account.setMoney(10000f ); as.createAccount(account); } @Test public void testDelete () { ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml" ); IAccountService as = ac.getBean("accountService" ,IAccountService.class); as.deleteAccount(1 ); } }
使用init()可以将重复代码抽出来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 public class AccountServiceTest { private ApplicationContext ac; private IAccountService as; @Before public void init () { ac = new ClassPathXmlApplicationContext("beans.xml" ); 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的依赖
1 2 3 4 5 <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:指定注释类所在的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @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); } }
即可正常执行