Spring笔记8 Spring整合Junit

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没有用
一波分析:

解决方法:

  1. 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以上的版本

  1. 使用junit的@RunWith注解将原有的main()替换成spring提供的

  2. 用@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);
    }

}

即可正常执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值