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);
    }
}
相关推荐
xiaogai_gai9 分钟前
钉钉数据集成到金蝶云星空案例分享:传给钉钉后,回传金蝶字段
java·前端·钉钉
摇滚侠9 分钟前
云原生 Java 架构师的第一课 K8s+Docker+KubeSphere+DevOps 19-25
java·云原生·kubernetes
标致的钢铁侠15 分钟前
c# 温故而知新: 线程篇(一)
java·jvm·c#
宠友信息18 分钟前
资源权限与钱包流水在即时通讯源码后端架构中的设计
java·spring boot·redis·websocket·缓存
不知名的老吴20 分钟前
浅谈:编程语言中的那些「锁」事(二)
java·开发语言
程序员小八77722 分钟前
AOP 切面
java
地铁潜行者36 分钟前
从单体思维到微服务:服务拆分与组件选型实践
java·后端
花生了什么事o36 分钟前
线程池参数调优:corePoolSize 怎么设置
java·后端
灵性(๑>ڡ<)☆37 分钟前
Java学习笔记 --面向对象进阶
java·笔记·学习
写了20年代码的老程序员1 小时前
Java Lambda 类型安全查询是怎么实现的?从字节码层面拆一遍
java·开源