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

SSM框架之Spring集成Junit

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

SSM框架之Spring集成Junit

Spring集成Junit 1、原始Junit测试Spring的问题

在测试类中,每个测试方法都有以下两行代码

ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);

这两行代码的作用是获取容器,如果没有,直接会提示空指针异常。

2、解决方案

让SpringJunit负责创建Spring容器,但是需要进行测试Bean直接在测试类中进行注入

3、Spring集成Junit步骤

(1)导入spring集成Junit的坐标
(2)使用@Runwith注解替换原来的运行期
(3)使用@ContextConfiguration指定配置文件或配置类
(4)使用@Autowired注入需要测试的对象
(5)创建测试方法进行测试

4、举个例子

创建xml配置文件



4.0.0

Spring_ssm2
itheima_spring_ioc_annotation
1.0-SNAPSHOT


    
        mysql
        mysql-connector-java
        5.1.32
    

    
        c3p0
        c3p0
        0.9.1.2
    

    
        com.alibaba
        druid
        1.1.10
    

    
        junit
        junit
        4.12
    

    
        org.springframework
        spring-context
        5.0.5.RELEASE
    

    
        org.springframework
        spring-test
        5.0.5.RELEASE
    



创建java文件

package com.itheima.test;

import com.itheima.config.SpringConfiguration;
import com.itheima.service.UserService;
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;

import javax.sql.DataSource;
import java.sql.SQLException;

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {

    @Autowired
    private UserService userService;

    @Autowired
    private DataSource dataSource;

    @Test
    public void test1() throws SQLException {
        userService.save();
        System.out.println(dataSource.getConnection());
    }
}


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

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

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