junit测试找不到数据库

在过去的十年中,我们已经编写了成千上万的JUnit3测试,现在正尝试将结果合并到数据库中,而不是分散的日志文件中。 事实证明,扩展TestCase类非常容易做到这一点。 注意:这种方法并不直接适用于JUnit4或其他测试框架,但是通常可以做类似的事情。

被测类及其测验

出于演示目的,我们可以使用单个方法来定义一个类进行测试。

public class MyTestedClass {public String op(String a, String b) {return ((a == null) ? "" : a) + ":" + ((b == null) ? "" : b);}
}

具有单个要测试方法的类比您想象的要少的限制。 在前面提到的数千个测试中,我们仅测试了四种方法。

这是上述类的一些测试。

public class MySimpleTest extends SimpleTestCase {private MyTestedClass obj = new MyTestedClass();public void test1() {assertEquals("a:b", obj.op("a", "b"));}public void test2() {assertEquals(":b", obj.op(null, "b"));}public void test3() {assertEquals("a:", obj.op("a", null));}public void test4() {assertEquals(":", obj.op(null, null));}public void test5() {// this will failassertEquals(" : ", obj.op(null, null));}
}

使用TestListener捕获基本信息

JUnit3允许向侦听器添加其测试过程。 在测试运行之前和之后以及测试失败或有错误(引发异常)的任何时间调用此侦听器。 该TestListener将基本测试信息写入System.out,以作为概念证明。 修改它以将信息写入数据库,JMS主题等很容易。

public class SimpleTestListener implements TestListener {private static final TimeZone UTC = TimeZone.getTimeZone("UTC");private long start;private boolean successful = true;private String name;private String failure = null;SimpleTestListener() {}public void setName(String name) {this.name = name;}public void startTest(Test test) {start = System.currentTimeMillis();}public void addError(Test test, Throwable t) {// cache information about error.successful = false;}public void addFailure(Test test, AssertionFailedError e) {// cache information about failure.failure = e.getMessage();successful = false;}/*** After the test finishes we can update the database with statistics about* the test - name, elapsed time, whether it was successful, etc.*/public void endTest(Test test) {long elapsed = System.currentTimeMillis() - start;SimpleDateFormat fmt = new SimpleDateFormat();fmt.setTimeZone(UTC);System.out.printf("[%s, %s, %s, %d, %s, %s]\n", test.getClass().getName(), name, fmt.format(new Date(start)),elapsed, failure, Boolean.toString(successful));// write any information about errors or failures to database.}
}

生产TestListener应该在错误和失败方面做更多的事情。 我将其忽略,以便专注于更广泛的问题。

该侦听器不是线程安全的,因此我们将要使用Factory模式为每个测试创建一个新实例。 我们可以在工厂中创建重量级对象,例如,在工厂中打开SQL DataSource并将新的Connection传递给每个实例。

public class SimpleTestListenerFactory {public static final SimpleTestListenerFactory INSTANCE = new SimpleTestListenerFactory();public SimpleTestListenerFactory() {// establish connection data source here?}public SimpleTestListener newInstance() {// initialize listener.SimpleTestListener listener = new SimpleTestListener();return listener;}
}

如果我们知道测试框架是纯串行的,则可以通过创建缓冲区并在startTest()中调用System.setOut(),然后在endTest()中还原原始System.out来捕获所有控制台输出。 只要测试永不重叠,此方法就行得通,否则会引起问题。 但是,这可能会出现问题– IDE可能具有自己的允许并行执行的测试运行程序。

我们用自己的方法覆盖标准的run()方法,该方法在调用现有的run()方法之前创建并注册一个侦听器。

public class SimpleTestCase extends TestCase {public void run(TestResult result) {SimpleTestListener l = SimpleTestListenerFactory.INSTANCE.newInstance();result.addListener(l);l.setName(getName());super.run(result);result.removeListener(l);}}

现在,我们将预期的结果发送到System.out。

[MySimpleTest, test1, 8/2/15 11:58 PM, 0, null, true]
[MySimpleTest, test2, 8/2/15 11:58 PM, 10, null, true]
[MySimpleTest, test3, 8/2/15 11:58 PM, 0, null, true]
[MySimpleTest, test4, 8/2/15 11:58 PM, 0, null, true]
[MySimpleTest, test5, 8/2/15 11:58 PM, 4, expected same:<:> was not:< : >, false]

使用外观和TestListener捕获呼叫信息

这是一个好的开始,但我们可能会做得更好。 在上面提到的数千个测试中,仅调用了4种方法-如果我们可以捕获这些调用的输入和输出值,则将非常强大。

如果由于某些原因不接受AOP,则可以使用AOP或日志记录外观包装这些功能。 在简单的情况下,我们可以简单地捕获输入和输出值。

public class MyFacadeClass extends MyTestedClass {private MyTestedClass parent;private String a;private String b;private String result;public MyFacadeClass(MyTestedClass parent) {this.parent = parent;}public String getA() {return a;}public String getB() {return b;}public String getResult() {return result;}/*** Wrap tested method so we can capture input and output.*/public String op(String a, String b) {this.a = a;this.b = b;String result = parent.op(a, b);this.result = result;return result;}}

我们像以前一样记录基本信息,并添加一些新代码来记录输入和输出。

public class AdvancedTestListener extends SimpleTestListener {AdvancedTestListener() {}/*** Log information as before but also log call details.*/public void endTest(Test test) {super.endTest(test);// add captured inputs and outputsif (test instanceof MyAdvancedTest) {MyTestedClass obj = ((MyAdvancedTest) test).obj;if (obj instanceof MyFacadeClass) {MyFacadeClass facade = (MyFacadeClass) obj;System.out.printf("[, , %s, %s, %s]\n", facade.getA(), facade.getB(), facade.getResult());}}}
}

日志现在显示基本信息和呼叫详细信息。

[MyAdvancedTest, test2, 8/3/15 12:13 AM, 33, null, true]
[, , null, b, :b]
[MyAdvancedTest, test3, 8/3/15 12:13 AM, 0, null, true]
[, , a, null, a:]
[MyAdvancedTest, test4, 8/3/15 12:13 AM, 0, null, true]
[, , null, null, :]
[MyAdvancedTest, test1, 8/3/15 12:13 AM, 0, null, true]
[, , a, b, a:b]

我们希望将基本详细信息和呼叫详细信息相关联,但是通过添加唯一的测试ID可以轻松实现。

在现实世界中,这种方法还不够,在单个测试中,被测方法可能被多次调用。 在这种情况下,我们需要一种缓存多组输入和输出值的方法,或者扩展侦听器,以便我们可以在每个涵盖方法的末尾调用它。

通过将结果编码为XML或JSON而不是简单的列表,可以使结果更具扩展性。 这将使我们仅捕获感兴趣的值或轻松处理将来添加的字段。

[MyAdvancedTest, test2, 8/3/15 12:13 AM, 33, null, true]
{"a":null, "b":"b", "results":":b" }
[MyAdvancedTest, test3, 8/3/15 12:13 AM, 0, null, true]
{"a":"a", "b":null, "results":"a:" }
[MyAdvancedTest, test4, 8/3/15 12:13 AM, 0, null, true]
{"a":null, "b":null, "results":":" }
[MyAdvancedTest, test1, 8/3/15 12:13 AM, 0, null, true]
{"a":" a", "b":"b", "results":" a:b" }

捕获

现在,我们可以通过重放捕获的输入来重新运行测试,但是盲目比较结果存在两个问题。 首先,如果我们只关心单个值,这将是很多不必要的工作。 其次,许多测试是不确定的(例如,它们使用随时间变化的固定数据甚至实时数据),而我们不关心的事情可能会改变。

这不是一个容易的问题。 如果幸运的话,测试将遵循标准模式,我们可以对正在执行的测试做出很好的猜测,但需要手动进行验证。

首先,我们需要使用捕获某些或所有方法调用的外观包装测试方法的结果。 调用历史记录应该以一种我们以后可以重播的形式提供,例如一系列方法名称和序列化参数。

其次,我们需要包装TestCase assertX方法,以便捕获最近的方法调用以及传递给assert调用的值(当然还有结果)。

通过示例最容易展示和删除该过程。 让我们从一个简单的POJO开始。

public class Person {private String firstName;private String lastName;public String getFirstName() { return firstName; }public String getLastName() { return lastName; }
}

在这种情况下,我们的外观仅需要记录方法名称。

典型的测试方法是

public void test1() {Person p = getTestPerson();assertEquals("John", p.getFirstName());assertEquals("Smith", p.getLastName());
}

使用包装的assertX方法

static PersonFacade person;public static void assertEquals(String expected, String actual) {// ignoring null handling...boolean results = expected.equals(actual);LOG.log("assertEquals('" + expected + "',"+person.getMethodsCalled()+ ") = " + results);person.clearMethodsCalled();if (!results) {throw new AssertionFailedError("Expected same:<" + expected + " > was not:<" + actual + ">");}
}

所以我们会得到像

assertEquals('John', getFirstName()) = true;
assertEquals('Smith', getLastName()) = false;

不难看出如何通过测试框架来解析它,但是现在还为时过早。 第二种测试方法是

public void test1() {Person p = getTestPerson();assertEquals("john", p.getFirstName().toLowerCase());
}

并且我们的简单代码不会捕获toLowerCase() 。 我们的日志将错误记录:

assertEquals('John', getFirstName()) = false;

更为病理的情况是:

public void test1() {Person p = getTestPerson();LOG.log("testing " + p.getFirstName());assertEquals("john", "joe");
}

断言与包装的类无关。

有明显的创可贴,例如,我们可以捕获外观中的返回值,但这是一个非常深的兔子洞,我们希望远离它。 我认为答案是做出合理的第一次尝试,手动验证结果,然后再做。 (替代:将测试重写为可以捕获的形式。)

翻译自: https://www.javacodegeeks.com/2015/08/adding-database-logging-to-junit3.html

junit测试找不到数据库

junit测试找不到数据库_将数据库日志添加到JUnit3相关推荐

  1. junit测试类叫什么名字_使用Junit测试名称

    junit测试类叫什么名字 命名测试 当我们创建Junit测试时,通常没有方法名称的实际使用. Junit运行器使用反射来发现测试方法,并且从版本4开始,您不再被限制以test开始方法的名称. 测试方 ...

  2. junit测试设置不回滚_正确设置JUnit测试名称

    junit测试设置不回滚 寻找好名字是手工软件的挑战之一. 您需要随时随地找到它们-类,方法,变量,仅举几例. 但是,什么使名字成为好名字呢? 引用Oncle Bob的话:"三件事:可读性, ...

  3. 如何避免循环查询数据库_与数据库无关的查询是不可避免的

    如何避免循环查询数据库 As the amount of data managed by an organization grows, the difficulty of managing and q ...

  4. tidb数据库_异构数据库复制到TiDB

    tidb数据库 This article is based on a talk given by Tianshuang Qin at TiDB DevCon 2020. 本文基于Tianshuang ...

  5. sql还原数据库备份数据库_有关数据库备份,还原和恢复SQL面试问题–第一部分

    sql还原数据库备份数据库 So far, we've discussed a lot about database backup-and-restore process. The backup da ...

  6. mysql分布式数据库_分布式数据库搭建详细教程

    由于业务本身的需求,有时需要构建分布式数据库.一个具有较好设计的分布式数据库,对于用户(调用者)来说透明,跟使用本地数据库一样. 本文准备使用中间件的架构,实现分布式数据库的构建.简单点说,调用者与中 ...

  7. 操作 神通数据库_国产数据库最好的时代

    全文约2580字,阅读约15分钟 近日,墨天轮发布了2020年新一期的国产数据库名单,东方国信完全自主研发的分布式分析型数据库CirroData名列其中. "墨天轮"是国内数据库领 ...

  8. sql还原数据库备份数据库_有关数据库备份,还原和恢复SQL面试问题–第二部分

    sql还原数据库备份数据库 In this article, we'll walk through, some of the refined list of SQL Server backup-and ...

  9. sql还原数据库备份数据库_有关数据库备份,还原和恢复SQL面试问题–第IV部分

    sql还原数据库备份数据库 In this article, we'll see the how the backup-and-restore meta-data tables store the i ...

最新文章

  1. CF375D Tree and Queries(dsu on tree)
  2. 学习js权威指南第五站 ---- 数组
  3. matlab验证Ross随机过程(第二版)P19页的结果
  4. android os5.0 优点,Funtouch OS升级5.0 性能大幅提升
  5. ubuntu 13.04 找回丢失的grub2
  6. 谈谈Objective-C的警告 (转)
  7. 【科普篇】推荐系统之矩阵分解模型
  8. 单板剥皮机行业调研报告 - 市场现状分析与发展前景预测(2021-2027年)
  9. vue项目中使用sass的方法
  10. linux列出组_如何列出Linux中的所有组?
  11. 对象关系映射文件详解
  12. VC++ 添加用户环境变量
  13. 常用算法案例之贪心法(C语言)
  14. CAN通讯与RS485通讯区别
  15. appicon一键生成网站
  16. 【修真院“善良”系列之十九】他删库了他跑路了
  17. byte最大值最小值的问题
  18. 大屏监控系统实战(1)-项目介绍
  19. C语言高级应用---操作linux下V4L2摄像头应用程序
  20. 太火爆了!这一款小游戏火到把服务器搞瘫痪,合成大西瓜

热门文章

  1. jzoj6276-[Noip提高组模拟1]树【线段树,扫描线,倍增】
  2. P4231-三步必杀【差分】
  3. Spark SQL(八)之基于物品的相似度公式
  4. Unicode与UTF-8的区别
  5. 数据库连接池的选择及其开发配置
  6. 115个Java面试题和答案——终极列表(上)
  7. Java魔法堂:URI、URL(含URL Protocol Handler)和URN
  8. 11 个简练的 Java 性能调优技巧
  9. Node.JS第二讲笔记
  10. java实现遍历树形菜单方法——Dao层