您的位置:首页 > 其它

基于SSM或者SSH的三种单元测试方式

2017-07-26 23:16 741 查看
今天总结一下三种单元测试方法,这个废话不多说,直接上代码。

第一种方式(通过配置文件+原始方式获取bean):

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yuan.service.impl.TeacherServiceImpl;

public class TeacherServiceTest {

@Test

public void testTeacher(){

ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-yuan-service.xml");

TeacherServiceImpl bean = (TeacherServiceImpl)ctx.getBean("teacherService");

System.out.println(bean.queryAll());

}

}



第二种方式(通过配置文件+IOC注入bean):

import javax.annotation.Resource;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.test.context.ContextConfiguration;

import com.yuan.service.TeacherService;

/**

* 两种测试方法

* 类上边的两个注解都是需要的, 缺一不可

* @author yhl

*

*/

@RunWith(org.springframework.test.context.junit4.SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations="classpath:spring-yuan-service.xml")

public class SpringTest {

@Resource

public TeacherService teacherService;

@Test

public void test1(){

System.out.println(teacherService.queryAll());

}

}

第三种方式(通过配置文件+IOC注入bean+继承AbstractJUnit4SpringContextTests):

import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

@ContextConfiguration(locations = {"classpath:spring-config-test.xml"})

public class AppTest extends AbstractJUnit4SpringContextTests{

@Resource
public TeacherService teacherService;

@Test
public void test1(){
System.out.println(teacherService.queryAll());
}

}

配置文件其实没什么说的,简单来说就是,自动扫描包,还有数据库连接信息,这些自己配置吧。

还要jar,这个测试主要是junit-4.9.jar和spring-test-3.2.0.RELEASE.jar。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Junit 单元测试