测试数据与代码分离的测试(2)

发表于:2014-02-27来源:豆瓣作者:@行知-追寻技术之美点击数: 标签:测试数据
@Source( data.xls )//Excel source public void testAccessCheck_Excel(String userName, String pw, boolean expected) { assertEquals(expected, UserAccess. accessCheck(userName, pw)); } } 运行结果如下:

  @Source( "data.xls" )//Excel source

  public void testAccessCheck_Excel(String userName, String pw, boolean expected) {

  assertEquals(expected, UserAccess. accessCheck(userName, pw));

  }

  }

  运行结果如下:

image

  3. 数据库作为数据源

  同样,Feed4junit也支持数据库数据源,这里不做详细的介绍:其原理和上面文件数据源差不多,样例代码如下:

  类上声明@Database:

  import static org.junit.Assert.assertEquals;

  import org.databene.benerator.anno.Database;

  import org.databene.benerator.anno.Source;

  import org.databene.feed4junit.Feeder;

  import org.junit.Test;

  import org.junit.runner.RunWith;

  import sample.code.UserAccess;

  /*

  * Feed4JUnit - Get Data from Database, all test methods can use the database data

  */

  @RunWith(Feeder.class)

  @Database(

  id = "testdb",

  url = "jdbc:mysql://localhost:5000/SAMPLE",

  driver = "com.mysql.jdbc.Driver",

  user = "admin",

  password = "admin")

  public class F4JfromDB {

  @Test

  @Source(id = "testdb", selector = "select * from TEST")

  public void testAccessCheck(String userName, String pw, String expected) {

  Boolean bSucess = UserAccess.accessCheck(userName.trim(), pw.trim());

  assertEquals(expected.trim(), bSucess.toString());

  }

  }

  测试方法上声明@Database

  @RunWith(Feeder.class)

  public class F4JfromDB_Method {

  @Test

  @Database(

  id = "testdb",

  url = "jdbc:mysql://localhost:5000/SAMPLE",

  driver = "com.mysql.jdbc.Driver",

  user = "admin",

  password = "admin")

  @Source(id = "testdb", selector = "select * from TEST")

  public void testAccessCheck(String userName, String pw, String expected) {

  Boolean bSucess = UserAccess.accessCheck(userName.trim(), pw.trim());

  assertEquals(expected.trim(), bSucess.toString());

  }

  }

  测试运行过程中,通过 url,driver 等信息建立数据连接,通过 selector 发出数据请求,最后完成查询并把数据传递给测试方法,数据在传递给方法的时候,会按数据表的列的顺序与参数进行匹配.

  4.最后

  Feed4JUnit 提供了对数据与代码分离的测试支持。只需要简单的注释,Feed4JUnit 就可以使用户很方便的实施数据与代码分离之间的测试,对于习惯了JUnit 测试框架的同学来说,是一个十分省力的利器。

  Feed4JUnit 同时还提供大量数据的随机测试和等价类测试等众多功能,这个留到后面再进行挖掘。

原文转自:http://www.wangyuxiong.com/archives/51662