论坛首页 综合技术论坛

JUnit In Action读书笔记(7) -- Managing resources with

浏览 1562 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-04-04   最后修改:2010-11-15

2.6.1 Managing resources with a fixture
    有时,一些tests是需要外部资源的,而这些资源的配置却很麻烦.这方面很典型的例子就是数据库的连接.而有时为了一个测试,我们得需要很复杂的data stuctures或一长串的随机输入.
            要是把这些很典型的setup代码也写进tests里的话,那可就显得有些傻了.毕竟我们要测试的不是搭建资源的能力--我们仅仅是需要一个稳定的测试环境.这里的测试环境set在JUnit里称为"test fixture".
    DEFINITION: ;fixture--The set of common resources or data that you need to run one or more tests.
    
    JUnit framework可以通过TestCase的setUp和tearDown方法来自动地创建和销毁.在运行每一个tests前,TestCase会自动调用setUp方法,而在每一个test完成之后TestCase也会自动调用tearDown.写测试代码时,我们之所以将很多相关的test method写入the same TestCase里的重要的原因是想share the fixture code.
    
    在实际中,现在many developers现在用mock objects或stubs来模拟数据库连接和其它更为复杂的资源的配置.
    
    数据库连接问题的例子就是一个很好的例子来说明我们为什么需要a fixture.若一个TestCase同时又包含了很多个数据库测试的话,这些连接都是需要一个对数据库的全新连接,利用JUnit中的fixture我们就可以很轻易地为每一个test都创建一个全新的连接,而无需replicating code.我们也可以很轻松地利用fixture创建新的input files.doing this means you do not have to carry your test files with your tests, and you always have a known state before the test is executed.
    我们也可以通过JUnit里Assert接口提供的一些utility methods来重用代码,下一节我们解释这个utility methods.

 

      JUnit design goals
   
    When it is easy to reuse a fixture between tests, you can write tests more quickly. Each time you reuse the fixture, you decrease the initial investment made when the fixture was created. The TestCase fixtures speak to JUnit’s third design goal:
        The framework must lower the cost of writing tests by reusing code.
    
    
2.6.2 Creating unit test methods

论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics