SSM项目中使用Junit进行单元测试

1、引入jar包
hamcrest-core-1.3.jar
junit-4.12.jar
spring-test-4.3.9.RELEASE.jar
其中要注意spring-test要与Spring版本一致, junit-4.12对应 hamcrest-core-1.3,最好不要改版本号

2、SSM项目中使用Junit进行单元测试_第1张图片
项目结构如图所示,新建log4j.properties,这是必须的,因为Junit单元测试用到log4j,log4j.properties的内容可自行百度,或参考以下代码:

log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

3.新建测试类
在test包下新建测试类,

package test;

import java.util.List;

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 entity.Course;
import service.CourseService;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml") 
public class BaseTest {
     
 
 //利用依赖注入
	@Autowired
	private CourseService courseService;
	
	@Test
	public void test_getAllCourse() {
     
		List<Course> courses=courseService.getAllCourse(35);
		System.out.println("查询数量为:"+courses.size());
	}
}

注意:@ContextConfiguration(locations = “classpath:applicationContext.xml”) 指的是Spring配置文件的位置,一定要注意拼写正确,否则可能无法正确找到文件

你可能感兴趣的:(毕设,SSM搭建服务器,java)