使用junit4测试Spring

1、环境搭建很简单,只需要将这这两个jar包(org.springframework.test-3.0.3.RELEASE.jar和junit-4.8.1.jar),和Spring的公用包以及其它的Jar包一起加入到项目中即可。

2、使用时,编写的测试类,需要继承类AbstractJUnit4SpringContextTests,同时需要指定Spring配置文件的路径,请看示例代码:

[java] view plain copy
 
  1. @ContextConfiguration(locations = { "/spring/applicationContext-memcached.xml" })  
  2. public class SpyMemcachedClientTest extends AbstractJUnit4SpringContextTests{  
  3.   
  4.     @Autowired  
  5.     private JoyMemcachedClient joyMemcachedClient;  
  6.   
  7.     @Test  
  8.     public void normal() throws InterruptedException {  
  9.   
  10.         String key = "consumer:1";  
  11.         String value = "admin";  
  12.   
  13.         joyMemcachedClient.set(key, 2, value);  
  14.         String result = joyMemcachedClient.get(key);  
  15.         assertEquals(value, result);  
  16.   
  17.         //Thread.sleep(3000);  
  18.         result = joyMemcachedClient.get(key);  
  19.         assertNotNull(result);  
  20.           
  21.         joyMemcachedClient.delete(key);  
  22.         //这么写会抛异常,无法自动转型  
  23.         result = joyMemcachedClient.get(key);  
  24.         assertNull(result);  
  25.     }  
  26. }  


3、测试方法必须是使用@Test指定(并不是测试类中所有的方法都是测试方法,使用@Test指定的才是),且返回值void,还不能有参数。

4、如果Spring配置文件中配置了数据库连接池,请不要使用JNDI方式配置。

原文地址:https://www.cnblogs.com/zxf330301/p/5397004.html