• spring的单元测试


    如果spring 4.3.18这个版本的spring要使用junit,需要使用junit的junit-4.12之上的版本。使用这个版本junit的时
    候需要引入hamcrest-all的jar包。之前的junit版本是不需要单独引入这个jar包的,因为之前版本把hamcrest-all的
    jar包集成进来了,从4.12开始,该jar包不集成,需要单独的引入。
    /**
    * 使用junit进行单元测试
    */
    public class JunitTest {
    @Test
    public void testSave(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    OrderService orderService = context.getBean(OrderService.class);
    //保存订单
    Orders order = new Orders();
    order.setId(1L);
    order.setCreate_user("张三");
    order.setCreateDate(new Date().toString().substring(0,20));
    order.setTotalMoney(9000D);
    OrderItem oi1 = new OrderItem();
    oi1.setId(1L);
    oi1.setPname("洗衣机");
    oi1.setPrice(900D);
    oi1.setNum(1);
    order.getOrderItems().add(oi1);
    OrderItem oi2 = new OrderItem();
    oi2.setId(2L);
    oi2.setPname("微波炉");
    oi2.setPrice(356D);
    oi2.setNum(2);
    order.getOrderItems().add(oi2);
    //执行保存
    orderService.save(order);
    }
    }
    如果每次都这样做spring的测试,理论上是可的但是,但是每个单元测试的方法中都要有创建spring工厂
    ,从工厂中获取对象的方法。比较复杂,我们可以使用spring 单元测试功能,来解决这个问题:
    如果要使用spring的单元测试,需要先引入spring 单元测试的jar包:
    /**
    * 使用junit进行单元测试
    */
    //指定在单元测试启动的时候创建spring的工厂类对象
    @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    //RunWith的value属性指定以spring test的SpringJUnit4ClassRunner作为启动类
    //如果不指定启动类,默认启用的junit中的默认启动类
    @RunWith(value = SpringJUnit4ClassRunner.class)
    public class JunitTest {
    @Autowired
    private OrderService orderService;
    @Test
    public void testSave(){
    // ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    // OrderService orderService = context.getBean(OrderService.class);
    //保存订单
    Orders order = new Orders();
    order.setId(1L);
    order.setCreate_user("张三");
    order.setCreateDate(new Date().toString().substring(0,20));
    order.setTotalMoney(9000D);
    OrderItem oi1 = new OrderItem();
    oi1.setId(1L);
    oi1.setPname("洗衣机");
    oi1.setPrice(900D);
    oi1.setNum(1);
    order.getOrderItems().add(oi1);
    OrderItem oi2 = new OrderItem();
    oi2.setId(2L);
    oi2.setPname("微波炉");
    oi2.setPrice(356D);
    oi2.setNum(2);
    order.getOrderItems().add(oi2);
    //执行保存
    orderService.save(order);
    }
    }
  • 相关阅读:
    github创建repo,本地导入git项目到github
    成功的GIT开发分支模型和策略
    示例可重用的web component方式组织angular应用模块
    git deployment strategy
    如何在linux中从源代码编译安装nodejs?
    some resource favor
    学而习之,成就学习
    C# 去掉代码前边空格(格式化代码)
    mvc重定向
    mvc cshtml 中赋值
  • 原文地址:https://www.cnblogs.com/duguangming/p/10922693.html
Copyright © 2020-2023  润新知