spring test配合junit4 实现单元测试

引入依赖

java 复制代码
<!--下面两个是测试相关的jar包-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>

测试类写法一:

java 复制代码
import com.imooc.spring.jdbc.entity.Employee;
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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class EmployeeDaoTest {

    @Autowired
    private EmployeeDao employeeDao;

    @Test
    public void findById() {
        Employee employee = employeeDao.findById(3308);
        System.out.println(employee);
    }
}

测试类写法二:

java 复制代码
import com.imooc.spring.jdbc.entity.Employee;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmployeeDaoTest {
    @Test
    public void findById() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        EmployeeDao employeeDao = context.getBean("employeeDao", EmployeeDao.class);
        Employee employee = employeeDao.findById(3308);
        System.out.println(employee);
    }
}
相关推荐
短剑重铸之日12 分钟前
《SpringCloud实用版》 Seata 分布式事务实战:AT / TCC / Saga /XA
后端·spring·spring cloud·seata·分布式事务
iRuriCatt16 分钟前
智慧景区管理系统 | 计算机毕设项目
java·前端·spring boot·vue·毕设
天空属于哈夫克334 分钟前
企业微信外部群运营升级:API 主动推送消息开发实战
java·数据库·mysql
qq_124987075337 分钟前
基于springboot的会议室预订系统设计与实现(源码+论文+部署+安装)
java·vue.js·spring boot·后端·信息可视化·毕业设计·计算机毕业设计
愿你天黑有灯下雨有伞43 分钟前
java动态渲染列导出以及分页列表
java
星火开发设计1 小时前
共用体 union:节省内存的特殊数据类型
java·开发语言·数据库·c++·算法·内存
2301_803554521 小时前
阻塞,非阻塞,同步,异步以及linux上的5种IO模型阻塞,非阻塞,信号驱动,异步,IO复用
java·服务器·网络
仰望星空_Star1 小时前
Java证书操作
java·开发语言
河北小博博1 小时前
分布式系统稳定性基石:熔断与限流的深度解析(附Python实战)
java·开发语言·python
岳轩子1 小时前
JVM Java 类加载机制与 ClassLoader 核心知识全总结 第二节
java·开发语言·jvm