❶ 如何使用junit测试javaweb工程
一:创建一个测试类,建议将测试类单独放在一个包中(在 maven 项目里有测试类专门的存放位置),新建一个Junit Test Case类,下一步
测试类的命名建议是你将要测试的类名+Test,然后点 Browse, 你可以选择要进行测试的类(一般选择 Service, 因为 Service 关心的是业务需求),用这种方式创建可以自动生成要测试类的测试类,你只需要进行测试代码的书写.
@Test
public void testqueryById(){
} @Test
public void testQueryAll(){
} @Test
public void testReceNumber(){
}123456789101112
如果里面有自动生成的代码,删除或注释即可…
二:配置 spring 和 junit 整合, junit 启动时加载 springIOC 容器,这里你需要 Spring-test jar包
@RunWith(SpringJUnit4ClassRunner.class) //告诉junitspring配置文件
@ContextConfiguration(locations = {"classpath:spring/spring-.xml"})123
同样的,在测试类中我们会调用 Service 的逻辑,由于我们使用的是 Spring+SpringMVC+ 持久化框架,所以要注入一个 IService 接口(这里我直接对 DAO 进行测试了)
@Autowired
private SeckillDao seckillDao;12
接下来是测试逻辑,在编写测试代码之前建议覆盖实体中的 toString 方法,不然打印会很麻烦.
@Test public void testqueryById(){ long id = 1000;
Seckill seckill = seckillDao.queryById(id);
System.out.println(seckill.getSeckillName());
System.out.println(seckill);
} //JAVA没有保存形参的记录,如果你在 中传了多个参数,那么需要声明它的形参对应的实参,否则 JVM 会显示找不到参数.声明方式稍后奉上
@Test public void testQueryAll(){
List<Seckill> seckills = seckillDao.queryAll(0, 100); for(Seckill seckill:seckills){
System.out.println(seckill);
}
}
@Test public void testReceNumber(){
Date killTime = new Date(); //对增加进行测试的时候,只要数据库增加了一条数据,我们就默认这个方法执行成功了
int updateCount = seckillDao.receNumber(1000L, killTime);
System.out.println("updateCount = "+updateCount);
}
解决JAVA不保存形参的记录
int receNumber(@Param("seckillId")long seckillId,@Param("killTime")Date killTime);
Seckill queryById(long seckillId); /**
* mysql的分页查询
* @param offset 告诉它实际的形参
* @param limit
* @return
*/
List<Seckill> queryAll(@Param("offset")int offset,@Param("limit")int limit);1234567891011
接下来我们根据他返回的结果和我们想要的结果对应就可以了. 测试类不用部署项目, 测试周期非常短, 而且可以进行专项测试. 测试类代码逻辑十分简单, 几乎不会出错. 如果结果不是预期的, 那么根据你的需求修改!
当然, 它的局限性也很打. 从单元测试不能看出页面传值的错误, 许多项目在服务器中的表现也不能模拟.
那么我们什么时候用junit呢?
当你的数据库操作非常复杂, 你不确定能输出你想要的值的时候, 相比用 debug 调试, 使用 Junit 是更方便的手段.或者新手出错概率非常大, 也不用在服务器中专门测试项目的表现, Junit 是个必备的工具!而且测试类的测试代码重用性很高.
如果你的数据和预期相悖, 那么修改业务逻辑; 否则, 查看页面是否有错! Junit在一定程度上减轻了我们业务代码调试的压力, 让我们关注于一点解决错误.
❷ 在spring和junit整合中出现java.lang.NoClassDefFoundError: javax/servlet/ServletContext错误
我印象里好像也出现过,我把我的配置方式给你说一下,你看能不能跑起来。
如果你是springMVC可以采用下面说的,springboot另说,更简单。
首先这几个jar得有:junit-4.12.jar、hamcrest-core-1.3.jar和spring-test-4.3.6.RELEASE.jar。
其次你看下我的Test类:
所以我填的是classpath:web/WEB-INF/applicationContext.xml
❸ 怎么创建junit4 注入spring 配置文件
1 建立一个test的目录,在此目录下放置所有的JunitTestCase类和TestCase的配置文件
2 将项目中的Spring配置文件(默认名称为applicationContext.xml)复制到test目录下,并重新命名为JunitTestConf.xml。
3 根据Junit测试的需要修改JunitTestConf.xml文件中的内容,如数据库连接等。
4 新建一个名为SpringConfForTest.java的类,在此类中配置Spring启动所需的配置文件,并启动Spring。此类的内容如下:
package test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.;
import com.soma.global.WebContextHolder;
public class SpringConfForTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
//Spring启动所需要的配置参数文件,其中test/JunitTestConf.xml文件中保存了数据库连接等参数,可根据具体情况做修改
String[] paths = new String[] {"test/JunitTestConf.xml", "com/soma/conf/applicationContext--hr.xml","com/soma/conf/applicationContext-.xml","com/soma/conf/applicationContext--bug.xml","com/soma/conf/applicationContext--change.xml","com/soma/conf/applicationContext--common.xml","com/soma/conf/applicationContext-service-hr.xml" };
//启动Spring,得到Spring环境上下文
ApplicationContext ctx = new (paths);
//在此类启动时,将Spring环境上下文保存到单根类WebContextHolder中,以提供给其它的测试类使用
WebContextHolder.getInstence().setApplicationContext(ctx);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void test(){
//必须要写一个test空方法,否则SpringConfForTest类不会启动
}
}
5 新建TestSuite类,类名为AllTests,类的内容如下所示:
package test;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import test.com.soma.domain.busilogic.hr.HrBusiLogicTest;
import test.com.soma.domain.service.hr.checkOverTimeDateTest;
@RunWith(Suite.class)
@Suite.SuiteClasses({
SpringConfForTest.class,
HrBusiLogicTest.class,
checkOverTimeDateTest.class
})
/**
* 批量执行Junit测试类,把类名写入到上面的Suite.SuiteClasses({})中,用逗号分隔
*/
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for test");
//$JUnit-BEGIN$
//$JUnit-END$
return suite;
}
}
注意:将SpringConfForTest.class放在第一个执行,以启动Spring配置环境,把自己的TestCase类放到后面,用逗号分开。在测试时,只要执行这个TestSuite类就可以了。
6 写自己的TestCase类,以CheckOverTimeDateTest.java为例子,文件内容如下:
public class CheckOverTimeDateTest {
private static HrTbovertimeManager hrTbovertimeManager;
private static ExcuteSqlDAO excuteSqlDAO;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
//从Spring上下文中得到hrTbovertimeManager接口类的实例
hrTbovertimeManager=(HrTbovertimeManager)BeanUtil.getBean("hrTbovertimeManager");
excuteSqlDAO = (ExcuteSqlDAO) BeanUtil.getBean("excuteSqlDAO");
}
@Test
public void testGetProjectList()throws Exception {
List<OvertimeDetailValue> overtimeDetailValueList = new ArrayList<OvertimeDetailValue>();
int index = 9;
for(int i = 1 ;i <= index;i++){
OvertimeDetailValue overtimeDetailValue = new OvertimeDetailValue();
overtimeDetailValue.setOtApplyDate("2009-05-0"+i);
overtimeDetailValueList.add(overtimeDetailValue);
}
String resultStr = hrTbovertimeManager.checkOverTimeDate(overtimeDetailValueList);
assertEquals("false", resultStr);
}
/**
* 导入2009-03月份出勤记录excel文件,返回null表示导入成功,需要先删除3月份的数据
*/
@Test
public void testSaveExcelDutyInformation() throws Exception{
// 在导入3月份出勤记录前先删除3月份的记录,执行delete from hr_tbtyinformation;
excuteSqlDAO.excuteSql("delete from hr_tbtyinformation where tydate>='2009-02-26' and tydate<='2009-03-25'");
// System.out.println("----------"+System.getProperty("user.dir")+"/src/test/ty200903.xls");
String fileName = System.getProperty("user.dir")
+ "/src/test/ty200903.xls";
assertNull(hrTbtyInformationManager.saveExcelDutyInformation(fileName));
}
}
说明:BeanUtil.getBean("")相当于WebContextHolder.getInstence().getApplicationContext().getBean(""),只是对此方法做了封装。
7 在Eclipse中,启动AllTests,选择“Run As JunitTest”,即可先启动Spring环境,再依次运行你自己所写的JunitTestCase,是不是很简单哪?赶快动手试试吧。
❹ 基于maven的web工程集成spring后在junit测试类中实例化容器后取不到Bean对象
Spring中的几种容器都支
持使用xml装配bean,包括:
XmlBeanFactory ,
,
,
XmlWebApplicationContext
使用web.xml中配置的spring启动方式与junit中装配的方式不同,与maven无关,你用junit测试XXservice,应该先把bean装配起来,不知道亲懂没
❺ spring test 怎么读取web-inf下的applicationcontext
假设Spring配置文件为applicationContext.xml
一、Spring配置文件在类路径下面
在Spring的java应用程序中,一般我们的Spring的配置文件都是放在放在类路径下面(也即编译后会进入到classes目录下)。
以下的项目,因为是用maven管理的,所以配置文件都放在“src/main/resources”目录下
这时候,在代码中就不可以使用来加载配置文件了,而应使用。
Java代码
=new("src/main/webapp/WEB-INF/applicationContext.xml");
然后获取相应的bean。
如果代码想用Junit测试框架来测试,则Spring提供了对Junit支持,还可以使用注解的方式:
Java代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/applicationContext.xml"})
只需要在相应的Test类前面加上此两个注解(第二个注解用来指明Spring的配置文件位置),就可以在Junit Test类使用中Spring提供的依赖注入功能。
下面是一个Spring管理下的Junit测试类:
Java代码
packagecom.sohu.group.service.external;
importjava.util.List;
importorg.junit.Test;
importorg.junit.runner.RunWith;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.test.context.ContextConfiguration;
importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"file:src/main/webapp/WEB-INF/applicationContext.xml"})
{
@Autowired
;
@Test
(){
List<String>list=suFriendService.getUserFollowerList("[email protected]");
System.out.println("------"+list);
}
}
❻ 如何用Junit4测试Spring框架下配置的类
如何用Junit4测试Spring框架下配置的类
前几天,我们在做Junit4的单元测试时,遇到了问题,就是Junit无法获得spring的配置环境,即Junit无法得到Spring创建的类实例。
在查阅了网上的一些资料和同事的帮助下,成功的解决了此问题。步骤如下:
1 建立一个test的目录,在此目录下放置所有的JunitTestCase类和TestCase的配置文件
2 将项目中的Spring配置文件(默认名称为applicationContext.xml)复制到test目录下,并重新命名为JunitTestConf.xml。
3 根据Junit测试的需要修改JunitTestConf.xml文件中的内容,如数据库连接等。
4 新建一个名为SpringConfForTest.java的类,在此类中配置Spring启动所需的配置文件,并启动Spring。此类的内容如下:
package test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.;
import com.soma.global.WebContextHolder;
public class SpringConfForTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
//Spring启动所需要的配置参数文件,其中test/JunitTestConf.xml文件中保存了数据库连接等参数,可根据具体情况做修改
String[] paths = new String[] {"test/JunitTestConf.xml", "com/soma/conf/applicationContext--hr.xml","com/soma/conf/applicationContext-.xml","com/soma/conf/applicationContext--bug.xml","com/soma/conf/applicationContext--change.xml","com/soma/conf/applicationContext--common.xml","com/soma/conf/applicationContext-service-hr.xml" };
//启动Spring,得到Spring环境上下文
ApplicationContext ctx = new (paths);
//在此类启动时,将Spring环境上下文保存到单根类WebContextHolder中,以提供给其它的测试类使用
WebContextHolder.getInstence().setApplicationContext(ctx);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void test(){
//必须要写一个test空方法,否则SpringConfForTest类不会启动
}
}
5 新建TestSuite类,类名为AllTests,类的内容如下所示:
package test;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import test.com.soma.domain.busilogic.hr.HrBusiLogicTest;
import test.com.soma.domain.service.hr.checkOverTimeDateTest;
@RunWith(Suite.class)
@Suite.SuiteClasses({
SpringConfForTest.class,
HrBusiLogicTest.class,
checkOverTimeDateTest.class
})
/**
* 批量执行Junit测试类,把类名写入到上面的Suite.SuiteClasses({})中,用逗号分隔
*/
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for test");
//$JUnit-BEGIN$
//$JUnit-END$
return suite;
}
}
注意:将SpringConfForTest.class放在第一个执行,以启动Spring配置环境,把自己的TestCase类放到后面,用逗号分开。在测试时,只要执行这个TestSuite类就可以了。
6 写自己的TestCase类,以CheckOverTimeDateTest.java为例子,文件内容如下:
public class CheckOverTimeDateTest {
private static HrTbovertimeManager hrTbovertimeManager;
private static ExcuteSqlDAO excuteSqlDAO;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
//从Spring上下文中得到hrTbovertimeManager接口类的实例
hrTbovertimeManager=(HrTbovertimeManager)BeanUtil.getBean("hrTbovertimeManager");
excuteSqlDAO = (ExcuteSqlDAO) BeanUtil.getBean("excuteSqlDAO");
}
@Test
public void testGetProjectList()throws Exception {
List<OvertimeDetailValue> overtimeDetailValueList = new ArrayList<OvertimeDetailValue>();
int index = 9;
for(int i = 1 ;i <= index;i++){
OvertimeDetailValue overtimeDetailValue = new OvertimeDetailValue();
overtimeDetailValue.setOtApplyDate("2009-05-0"+i);
overtimeDetailValueList.add(overtimeDetailValue);
}
String resultStr = hrTbovertimeManager.checkOverTimeDate(overtimeDetailValueList);
assertEquals("false", resultStr);
}
/**
* 导入2009-03月份出勤记录excel文件,返回null表示导入成功,需要先删除3月份的数据
*/
@Test
public void testSaveExcelDutyInformation() throws Exception{
// 在导入3月份出勤记录前先删除3月份的记录,执行delete from hr_tbtyinformation;
excuteSqlDAO.excuteSql("delete from hr_tbtyinformation where tydate>='2009-02-26' and tydate<='2009-03-25'");
// System.out.println("----------"+System.getProperty("user.dir")+"/src/test/ty200903.xls");
String fileName = System.getProperty("user.dir")
+ "/src/test/ty200903.xls";
assertNull(hrTbtyInformationManager.saveExcelDutyInformation(fileName));
}
}
说明:BeanUtil.getBean("")相当于WebContextHolder.getInstence().getApplicationContext().getBean(""),只是对此方法做了封装。
7 在Eclipse中,启动AllTests,选择“Run As JunitTest”,即可先启动Spring环境,再依次运行你自己所写的JunitTestCase
❼ junit 测试spring时报错 no bean named ‘bookBO ’的错
把spring配置文件贴出来看下,可能配置错了,也有可能是没起web服务器,容器里还没有这个bean
❽ junit测试时,spring怎么读放在WEB-INF/上的xml文件
配合spring-text.jar
类上面写注解
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config/application-context.xml")
config/application-context.xml是路径
再写一个text方法,加个注解@Text