1.如果你使用maven来管理web项目,那么建议将测试的内容放在src/test/java,如下为我的项目目录
习惯在src/test/java下建立和src/main/java中一样的包名用以测试该包中的测试.
2.测试的类名,通常是直接在需要测试的类名后加Test便可
3.测试类配置
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import cm.cn.po.HlPeople;
import cm.cn.service.HlPeopleService;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试
@ContextConfiguration(locations = "classpath:spring/applicationContext-*.xml") //加载配置文件,这里写你自己的spring配置文件的存放目录
public class HlPeopleServiceTest {
@Autowired
private HlPeopleService hlPeopleService;
@Test
public void selectPeopleById(){
/**测试代码**/
}
}
也可写个BaseJunit4Test类,这样每次新建测试类直接继承就好,不必每次注解了.BaseJunit4Test类如下
4.BaseJunit4Test类
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试
@ContextConfiguration(locations = "classpath:spring/applicationContext-*.xml") //加载配置文件
//------------如果加入以下代码,所有继承该类的测试类都会遵循该配置,也可以不加,在测试类的方法上///控制事务,参见下一个实例
//这个非常关键,如果不加入这个注解配置,事务控制就会完全失效!
//@Transactional
//这里的事务关联到配置文件中的事务控制器(transactionManager = "transactionManager"),同时//指定自动回滚(defaultRollback = true)。这样做操作的数据才不会污染数据库!
//@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
//------------
public class BaseJunit4Test{
}
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import cm.cn.po.HlPeople;
import cm.cn.service.HlPeopleService;
public class HlPeopleServiceTest extends BaseJunit4Test{
@Autowired
private HlPeopleService hlPeopleService;
@Test
public void selectPeopleById(){
int peopleId = 87;
HlPeople hlPeople = hlPeopleService.selectPeopleById(peopleId);
System.out.println(hlPeople.getAdresss());
}
}