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);
    }
}
相关推荐
Code季风13 分钟前
深度优化 spring 性能:从缓存、延迟加载到并发控制的实战指南
java·spring boot·后端·spring·缓存·性能优化
风象南20 分钟前
SpringBoot自定义RestTemplate的拦截器链
java·spring boot·后端
NCHUtianlin21 分钟前
JAVA生成PDF(itextpdf)
java·开发语言·pdf
yiridancan22 分钟前
终极剖析HashMap:数据结构、哈希冲突与解决方案全解
java·数据结构·算法·哈希算法
拼搏@2 小时前
第十六天,7月10日,八股
java·mybatis
Sylvia-girl6 小时前
Java——抽象类
java·开发语言
Touper.9 小时前
Redis 基础详细介绍(Redis简单介绍,命令行客户端,Redis 命令,Java客户端)
java·数据库·redis
m0_535064609 小时前
C++模版编程:类模版与继承
java·jvm·c++
虾条_花吹雪10 小时前
Using Spring for Apache Pulsar:Message Production
java·ai·中间件
tomorrow.hello10 小时前
Java并发测试工具
java·开发语言·测试工具