java测试单元:Junit框架配置详解

摘要

本文的核心内容在于帮助小白快速掌握Junit测试框架的配置和使用。

引言

在SSM WEB项目中,代码的开发顺序一般从dao层到service层再到controller层,如果前一层的代码有问题,那么后一层的功能实现必然会受到严重的影响,这就需要在开发过程中对dao层和service层一一进行测试。Junit测试框架的作用就展现在这里,配合logback等日志框架(不是必须,但建议使用),我们可以很方便的进行测试分析和查找bug。关于logback日志框架的配置见我的博客:Java日志框架:logback配置详解

正文

step1 配置pom.xml
在pom.xml中引入junit依赖,代码如下:

 <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13-beta-1</version>
            <!--作用范围指定为:test-->
            <scope>test</scope>
        </dependency>

step2 编写测试代码
在此之前,我已经完成了相应的maven+ssm web项目搭建以及dao层代码的编写,dao层中UserMapper.java的代码如下:

package com.dao;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper 
{	
	/**
	 * 	根据用户名查询对应密码
	 * */
	@Select("SELECT password FROM user WHERE name = #{name}")
	public String getPasswordByName(String name);
}

接下来编写测试代码。建议先编写一个空的BaseTest类,代码如下:

package com.test;

import org.junit.runner.RunWith;
//这里使用到了spring框架的test.jar包
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * 配置spring和junit整合,junit启动时加载springIOC容器 spring-test,junit
 */
@RunWith(SpringJUnit4ClassRunner.class)
//告诉junit spring配置文件
@ContextConfiguration(locations= {"classpath:spring/spring-dao.xml","classpath:spring/spring-service.xml"})
public class BaseTest 
{
//这里空置
}

然后后续的类都继承该类,这样就省略了@RunWith,@ContextConfiguration等重复的代码。
UserMapper.java的测试类UserMapperTest.java代码如下:

package com.test.dao;

import javax.annotation.Resource;

import org.junit.Test;
import com.dao.UserMapper;
import com.test.BaseTest;

public class UserMapperTest extends BaseTest
{
	@Resource
	private UserMapper userMapper;
	
	@Test
	public void testGetPasswordByName() 
	{
		String name = "chenran";
		String password = userMapper.getPasswordByName(name);
		if(password != null)
		{
			System.out.println("password:"+password);
		}
		else
		{
			System.out.println("用户不存在!");
		}
	}
}

运行结果(配置了logback框架):

在这里插入图片描述
忽略上面的红色warning。倒数第四行,可以看到根据用户名查询到的密码为:123456,与我们在数据库中设置的一致。
至此,Junit框架配置详解介绍工作已经完成。20190112

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值