spring测试类

1.测试需要的包


    <!-- 测试需要的包 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13-beta-2</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>


2.用ClassPathXmlApplicationContext对象写的测试类


public class TestService {
    @Test
    public void testQueryAll(){
        System.out.println("start");
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        EmpService empService = (EmpService) applicationContext.getBean("empService");
        System.out.println(empService.getClass());
        List<Emp> emps = empService.queryAll();
        for (Emp emp : emps) {
            System.out.println(emp);
        }
        System.out.println("end");

    }
}

3.前2步情况足够使用了,但是为了代码美观,用@RunWith@ContextConfiguration两个注解建一个TestBean类,然后测试类继承这个类。

	好处:代码美观

/*
* 用@RunWith和@ContextConfiguration两个注解建一个TestBean类
* */
package com.baizhi.my.test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)// 随着工厂环境的运行
@ContextConfiguration("classpath:spring.xml")// 需要指定配置文件
public abstract class TestBean {
}

/*
* 用测试类继承TestBean这个类
* */
package com.baizhi.my.service;

import com.baizhi.my.entity.Emp;
import com.baizhi.my.test.TestBean;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class TestEmpService extends TestBean {
    @Autowired
    EmpService empService;
    @Test
    public void selectAllEmps() {
        List<Emp> empList = new ArrayList<>();
        empList = empService.selectAllEmps();
        for (Emp emp : empList) {
            System.out.println(emp);
        }
    }
}


试了一下,还行
test

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值