基于 Spring 的单元测试

本文对比了普通单元测试与Spring单元测试的区别,介绍了如何利用Spring的@Autowired注解简化bean的注入过程,使测试更加便捷。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、普通的单元测试:

  在 Spring 中我们将 bean 交给 Spring IOC 容器管理,那么我们在需要使用 bean 时,也要去 IOC 容器中获取,因此我们需要先获取 IOC 容器对象,再从容器中获取我们需要的 bean,就如下面一样。


    import java.util.List;
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import cn.edu.pzhu.cg.entities.Employee;
    import cn.edu.pzhu.onlineshopping.bean.Customer;
    import cn.edu.pzhu.onlineshopping.service.CustomerService;

    public class TestClass {

        private CustomerService customerService;
        private ApplicationContext ctx;

        @Before
        public void init() {
            ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
            customerService = (CustomerService) ctx.getBean("customerService");
        }

        @Test
        public void checkUserName() {
            String name = "Jack";
            System.out.println(customerService.getCustomerByName(name));
        }


        @Test
        public void testAddCustomer() {
            Customer cus = new Customer(null, "Tom", "111", 0, "123", "null", null, null, null);
            customerService.addCustomer(cus);
        }

    }

我们需要先获取 IOC 容器,才能从容器中获取到我们需要的 bean,实在是麻烦。

二、Spring 的单元测试:

  在 Spring 的单元测试中我们只需要加上 @Autowired 就能自动为我们注入所需要的 bean,我们直接使用就是了。

使用步骤:

  1. 加入 jar 包:spring-test.4.3.7.RELEASE
  2. 在测试类上加上以下两个注解:

    • @RunWith(SpringJUnit4ClassRunner.class):使用 Spring 的 JUnit
    • @ContextConfiguration(locations= {“classpath:appliationContext.xml”}):指定 spring 配置文件的位置。
  3. 在所需要的 bean 上加上 @Autowired。


    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 cn.edu.pzhu.cg.service.EmployeeService;

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations= {"classpath:appliationContext.xml"})
    public class ServiceTest {

        @Autowired
        private EmployeeService employeeService;

        @Test
        public void testQueryByName() {
            String name = "Tom";
            System.out.println(employeeService.getEmpByName(name));
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值