这里是小知识啦,由于每次都要找之前的项目,这里记录一下,免得之后麻烦。java
咱们在作spring项目的时候,启动的时候spring容器确定是要注入不少的类,这些在单例的时候比较麻烦,要启动整个项目,加载spring容器才能正确处理各个实例之间的依赖关系。spring
这里咱们使用junit4来作单例猜想,相比于junit3的好处就是,junit4加入大量的注解功能,使得测试起来更加的方便快捷。app
首先咱们须要两个主要的jar包:junit四、spring-test,固然spring其余须要的包这里就不在赘述,按照本身的项目去添加便可。单元测试
好比说我要测试这个方法:
测试
@Service public class EmployeeService { @Autowired private EmployeeMapper employeeMapper; public Employee findEmployee(int id) { return employeeMapper.selectById(id); } }
由于这个方法里面有依赖关系,因此要启动spring的容器。还有的人确定说咱们不须要依赖,直接new嘛,这种状况在依赖关系比较复杂的状况下并无卵用,太麻烦了。因此我是这么作的:spa
import com.yangbo.one.base.BaseTest; import com.yangbo.one.persistence.model.Employee; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @Slf4j public class UserServiceTest extends BaseTest { @Autowired private EmployeeService employeeService; @Test public void testFindEmployee() throws Exception { Employee employee = employeeService.findEmployee(111); System.out.println("--------------------" + employee); log.info("用户{}是个大傻逼,哈哈……",employee.getName()); } }
这里面有个继承关系,是为了我在新建其余测试类的时候,不用每次都去加注解,总之就是为了省事。因此这里的继承的BaseTest是这么写的,这个是关键,以下:code
import junit.framework.TestCase; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class BaseTest extends TestCase{ }
一切就绪,只须要右键运行testEmployeeTest的方法便可,运行的结果以下:xml
2015-11-03 17:18:15,917 INFO [main] c.yangbo.one.service.UserServiceTest [UserServiceTest.java : 19] 用户sfadsfa是个大傻逼,哈哈……继承
至此,单元测试OK。简单吧,我也不知道为何我每次都回去找旧项目,多是由于只是知其然还不知其因此然的缘由吧!get