栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Junit写法及与spring整合过程详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Junit写法及与spring整合过程详解

junit之前的写法:

//在Before中注入service类
private IUserService userService;
  @Before
public void setUp() throws Exception {
//使用xml的方式
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//使用注解的方式
  ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
userService = applicationContext.getBean(IUserService.class);
 }

Spring与junit整合:

  不需要手动创建Spring容器, 自动把bean注入到测试类

1、导入spring-test的依赖, 需要junit


   org.springframework
   spring-test
   4.3.3.RELEASE

2、在测试类使用spring-test的注解

@RunWith(class)

@ContextConfiguration(指定配置文件)

//测试类运行的环境,在spring环境下运行,在测试类, 注入Spring容器的bean
@RunWith(SpringJUnit4ClassRunner.class)
//在创建spring容器时,指定加载哪个配置文件 - - 相当于之前的手动获取对象
@ContextConfiguration("classpath:applicationContext.xml")
public class UserServiceImplTest {

  @Autowired //注入IUserService
  private IUserService userService;
  
  @Test
  public void testFindUserById() {
    userService.findUserById(2);
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/133674.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号