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);
    }
}
相关推荐
翊谦4 小时前
Java Agent开发 Milvus 向量数据库安装
java·数据库·milvus
晓晓hh4 小时前
JavaSE学习——迭代器
java·开发语言·学习
查古穆5 小时前
栈-有效的括号
java·数据结构·算法
__土块__5 小时前
一次 Spring 事务传播机制源码走读:从误用 @Transactional 到理解嵌套事务的边界
spring·threadlocal·编程式事务·@transactional·事务传播·源码走读·requires_new
Java面试题总结5 小时前
Spring - Bean 生命周期
java·spring·rpc
硅基诗人5 小时前
每日一道面试题 10:synchronized 与 ReentrantLock 的核心区别及生产环境如何选型?
java
014-code5 小时前
String.intern() 到底干了什么
java·开发语言·面试
摇滚侠6 小时前
JAVA 项目教程《苍穹外卖-12》,微信小程序项目,前后端分离,从开发到部署
java·开发语言·vue.js·node.js
楚国的小隐士6 小时前
为什么说Rust是对自闭症谱系人士友好的编程语言?
java·rust·编程·对比·自闭症·自闭症谱系障碍·神经多样性
春花秋月夏海冬雪6 小时前
代码随想录刷题 - 贪心Part1
java·算法·贪心·代码随想录