Spring笔记5-spring与junit整合

整合原因

1、应用程序的入口main方法

2、junit单元测试中,没有main方法也能执行

        junit集成了一个mian方法。该方法会判断测试类中的 @Test注解,junit会让有test注解的方法执行。

3、junit不知道我们是否使用了spring框架,所以不会为我们读取配置文件或配置类创建spring的IOC容器。

整合配置

        1、导入spring整合junit的jar包。

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

        2、使用 spring的 @Runwith 注解替换junit的main方法。

        3. @ContextConfiguration注解告知spring容器的创建时时基于XML还是注解配置类

                属性:

                        class:指定注解类的字节码文件

                        location:指定XML的位置,加上cllasspath关键字,表示在类路径下

          使用spring5.x版本时,junit必须是4.1.2及以上版本,否则会有无法初始化的异常

package org.example.service;

import config.SpringConfiguration;
import junit.framework.TestCase;
import org.example.pojo.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)//替换junit的main方法
@ContextConfiguration(classes = SpringConfiguration.class)//指定spring的配置
public class AccountServiceTest extends TestCase {

    @Autowired
    private AccountService accountService; //加上注解后就可以使用自动注入了

    @Test
    public void testFindAll() {
        List<Account> all = accountService.findAll();
        for (Account account: all) {
            System.out.println(account);
        }
    }


    @Test
    public void testFindOne() {
        Account accountById = accountService.findAccountById(1);
        System.out.println(accountById);

    }
    @Test
    public void testFindSave() {
        Account account = new Account();
        account.setName("ddd");
        account.setMoney(100F);
        accountService.saveAccount(account);
    }

    @Test
    public void testFindUpdate() {
        Account account = new Account();
        account.setName("ddd");
        account.setMoney(10000F);
        account.setId(4);
        accountService.updateAccount(account);
    }

    @Test
    public void testFindDelete() {
        Account account = new Account();
        accountService.deleteAccount(4);
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值