Spring注解整合junit

注解整合junit

由于单元测试中会有大量的重复代码

为了,解决这个问题 我们可以使用注解的方式进行处理

spring整合junit的配置

1、先导入pom依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.5.RELEASE</version>
    <scope>test</scope>
</dependency>

2、使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的 @Runwith 可以在运行时将自动注入的属性添加到spring容器中去。

3、告知spring的运行器,spring和IoC创建是基于xml文件还是注解的,并且说明位置 @ContextConfiguration

  • locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
  • classes:指定注解类所在位置
// 原有的main方法不能创建容器,所以现在使用Spring提供的可以创建容器
@RunWith(SpringJUnit4ClassRunner.class)
// 容器通过@ContextConfiguration设置的方式创建
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    private AccountService as = null;

    @Test
    public void testFindAll(){
        //执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne(){
        //执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave(){
        Account account = new Account("嘿嘿嘿", 2000f);
        //执行方法
        as.saveAccount(account);
    }

    @Test
    public void testUpdate(){
        Account account = new Account(4,"嘿嘿嘿123", 2000f);
        //执行方法
        as.updateAccount(account);
    }

    @Test
    public void testDelete(){
        //执行方法
        as.deleteAccount(4);
    }

}

猜你喜欢

转载自www.cnblogs.com/jianzha/p/12612456.html
今日推荐