7.spring与mybatis整合中Junit的测试

1.添加测试需要依赖的jar包

注意版本,junit的版本最好不要低于spring-test的版本,还有就是spring-test的版本与其他spring的版本注意不要冲突

<!--Junit测试-->
<dependency> 
    <groupId>org.springframework</groupId>  
    <artifactId>spring-test</artifactId>  
    <version>4.0.2.RELEASE</version>  
</dependency>
<!-- 单元测试 -->
<dependency>
      <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <version>4.10</version>
        <scope>test</scope>
</dependency>


以上两个包是必须要引入的,特别是spring-test的jar包,不引入就无法在测试文件中使用@RunWith等注解

2.编写测试文件

package com.test.service.impl;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.test.pojo.User;
import com.test.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring/spring-mybaits.xml"})

public class UserServiceImplTest {
    @Autowired
    private static UserService userService;
    
    @BeforeClass
    public static void init() {//junit之前init spring
        ApplicationContext   context = new ClassPathXmlApplicationContext("classpath:spring/spring-mybaits.xml");
        userService = (UserService)context.getBean("userServiceImpl");
    }

    @Test
    public void testGetUserById() {
        User user=this.userService.getUserById(1);
        System.out.println("-----------------------");
        System.out.println(user);
        System.out.println("-----------------------");
    
    }

}
代码解释:

1.@RunWith(SpringJUnit4ClassRunner.class)

  • 让测试运行于Spring测试环境,Spring框架在org.springframework.test.annotation 包中提供了常用的Spring特定的注解集,如果你在Java5或以上版本开发,可以在测试中使用它

2.@ContextConfiguration(locations={"classpath:spring/spring-mybaits.xml"})

       微笑 locations:可以通过该属性手工指定 Spring 配置文件所在的位置,可以指定一个或多个 Spring 配置文件。如:@ContextConfiguration(locations={“spring1.xml”,”spring2.xml”}),locations路径为在classes文件夹下或Maven resources下,q且配置文件下路径用classpath:指定,否则特殊情况下识别路径有误。

       微笑 若写classpath*:spring-mvc.xml 和 classpath*:spring-mybatis.xml代表所有资源文件遍历,首先会查main资源,之后查找test资源

3.@BeforeClass

由于junit运行单个文件的时候并没启动容器,也就无法进行实例化,使用service,那么@autowrid注解就是无效的。所以要在注入service之前执行init()方法,对该service进行实例化才能调用其中的方法。








  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值