junit测试和spring整合

  • 2019 年 10 月 30 日
  • 筆記

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/luo4105/article/details/72865519

Junit简介

Junit是十分好的单元测试工具,根据敏捷开发中测试驱动开发的思想,开发前应该先写单元测试和测试用例,再写实现方法,这样可以验证方法的正确与否,同时对方法重构后,执行一下写好的单元测试,也可以很明了的清楚重构是否损坏其他代码。

Eclipse默认带有junit插件,没有的说明版本太低,请自行百度Eclipse安装junit

单元测试

单元测试就是单纯的测试单一功能的实现,在单元测试中,不应该依赖spring容器之类的。

在项目中导入junit,写好测试方法,前些加@Test就可以了

用eclispe开始创建测试用例

运行测试用例

集成测试

集成测试可以使用spring的推荐的测试工具:spring-test.jar

也可以使用:junit

使用junit测试

测试mybatis的dao接口

实际上是加载mybatis的配置文件,获得mybatis的sqlsessionfactory和sqlsession,再获得mapper接口对象,并执行测试方法。

public classUserMapperTest {        private static SqlSessionFactory ssf = null;      private static SqlSession sqlSession = null;      private static UserMapper mapper = null;      //要测试的mapper接口对象        static {         // junit 找文件从src或WebContent上一级开始找,即classpath         try {             ssf = newSqlSessionFactoryBuilder().build(Resources.getResourceAsReader("com/lc/config/mybatis.xml"));             sqlSession = ssf.openSession();             mapper = sqlSession.getMapper(UserMapper.class);         }catch(IOException e) {             e.printStackTrace();         }      }        @Test      public void select() {         List<User>userlist= mapper.select();         for (User user : userlist) {             System.out.println(user);         }      }        @Test      public void delete() {         if (mapper.delete(1) > 0) {             sqlSession.rollback();             System.out.println("del success");             sqlSession.close();         }      }  }

测试service方法

实际上是加载spring配置,得到spring容器,在spring容器中拿到service的bean,并掉用其方法。

public classLogServiceTest {        private LogService logService;        @Before      public void setUp() throws Exception {         @SuppressWarnings("resource")         ClassPathXmlApplicationContextcontext= newClassPathXmlApplicationContext(                new String[] { "spring/spring-config.xml"});         context.start();         logService = context.getBean(LogService.class);      }        @Test      public void testSelectOne() {         Loglog= logService.selectOne(1);         System.out.println(log);      }        @Test      public void testSelect() {         Loglog= newLog();         List<Log>list= logService.select(log);         System.out.println(list);      }        @Test      public void testSelectByPage() {         Loglog= newLog();         PageInfo<Log>page= logService.selectByPage(log, null);         System.out.println(JSON.toJSONString(page));      }        @Test      public void testInsert() {         Loglog=newLog();         log.setUsername("xudong");         logService.insert(log);      }  }

测试controller

这里实际上是模拟http请求去调用controller接口,判断返回的数据是否正常

public classUserControllerTest {        @Before      public void setUp() throws Exception {      }        @Test      public void testSelectOne() throws IOException {         InputStreamis = new HttpUtil().doGet("http://localhost:8080/hotchPotch-web/system/user/selectOne?id=1");         Stringresult= newStreamUtil().inputStreamToString(is, "utf-8");         System.out.println(result);      }        class HttpUtil {          InputStream doGet(String urlstr) throws IOException {             URL url= new URL(urlstr);             HttpURLConnection conn= (HttpURLConnection) url.openConnection();             conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");             InputStream inputStream= conn.getInputStream();             return inputStream;          }      }        class StreamUtil {          public StringinputStreamToString(InputStream is, String charset)throwsIOException {             byte[] bytes = newbyte[1024];             int byteLength = 0;             StringBuffer sb = new StringBuffer();             while((byteLength = is.read(bytes)) != -1) {                 sb.append(new String(bytes, 0, byteLength, charset));             }             return sb.toString();          }      }  }

说说缺点

1.每执行一个测试方法都要加载spring配置文件,如果spring容器中需要加载的bean十分多,那么十分耗时。

2.数据库数据改变后不能回滚。

使用spring-test.jar和junit4测试

优点是

1.只需加载一次spring配置文件

2.支持数据回滚

3.支持spring注入,不需要使用getBean的方式获得spring容器的bean。

Transaction中的参数是事务bean的id

@RunWith(SpringJUnit4ClassRunner.class)  @ContextConfiguration({"classpath:spring/spring-config.xml"})  @Transactional(transactionManager="txManager")  public classLogServiceTest {        @Resource      private LogService logService;        @Test      public void testSelect() {         Loglog= newLog();         List<Log>list= logService.select(log);         System.out.println(list);      }        @Test      @Rollback(true)      public void testInsert() {         Loglog=newLog();         log.setUsername("xudong2");         logService.insert(log);      }  }

Java中,根据注解是可以继承的原理,我们可以抽象出加载Spring这些配置的注解在一个父类中,子类只需要专心写好测试方法就可以。

父类

@RunWith(SpringJUnit4ClassRunner.class)  @ContextConfiguration({"classpath:spring/spring-config.xml"})  @Transactional(transactionManager="txManager")  public classSpringTestRunner {    }

子类

public classLogServiceTestextendsSpringTestRunner {        @Resource      private LogService logService;        @Test      public void testSelect() {         Loglog= newLog();         List<Log>list= logService.select(log);         System.out.println(list);      }        @Test      @Rollback(true)      public void testInsert() {         Loglog=newLog();         log.setUsername("xudong2");         logService.insert(log);      }  }

使用log4j输出日志

简单方法

Spring配置会自动扫描源码包下是否存在log4j.properties,只需要把log4j.properties放在源码包下就可以了

改写SpringJUnit4ClassRunner类

public classJUnit4ClassRunner extends SpringJUnit4ClassRunner {       static{          try {              Log4jConfigurer.initLogging("classpath:config/log4j.xml");          } catch (FileNotFoundException ex) {              System.err.println("Cannot Initialize log4j");          }     }       publicJUnit4ClassRunner(Class<?> clazz) throwsInitializationError {          super(clazz);     }  }

测试类用SpringJUnit4ClassRunner的运行

@RunWith(JUnit4ClassRunner.class)