`

Digester 1.1 单元测试之RuleTestCase

阅读更多

    前面还记得有前辈说过看一个开源项目在不懂的情况下要去努力的去看它的单元测试,这样就能更好的领悟作者的思想。首先我们先看一下单元测试用的一些xml。

<!-- Test1.xml -->
<?xml version="1.0"?>
<employee firstName="First Name" lastName="Last Name">
  <address type="home" street="Home Street" city="Home City"
                        state="HS" zipCode="HmZip"/>
  <address type="office" street="Office Street" city="Office City"
                          state="OS" zipCode="OfZip"/>
</employee>


首先来看第一个单元测试:

package org.apache.commons.digester;


import java.io.InputStream;
import java.io.IOException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;


/**
 * <p>Test Case for the Digester class.  These tests perform parsing of
 * XML documents to exercise the built-in rules.</p>
 *
 * @author Craig R. McClanahan
 * @version $Revision: 1.5 $ $Date: 2001/10/11 00:28:42 $
 */

public class RuleTestCase extends TestCase {


    // ----------------------------------------------------- Instance Variables


    /**
     * The digester instance we will be processing.
     */
    protected Digester digester = null;


    // ----------------------------------------------------------- Constructors


    /**
     * Construct a new instance of this test case.
     *
     * @param name Name of the test case
     */
    public RuleTestCase(String name) {

        super(name);

    }


    // --------------------------------------------------- Overall Test Methods


    /**
     * Set up instance variables required by this test case.
     */
    public void setUp() {

        digester = new Digester();

    }


    /**
     * Return the tests included in this test suite.
     */
    public static Test suite() {

        return (new TestSuite(RuleTestCase.class));

    }


    /**
     * Tear down instance variables required by this test case.
     */
    public void tearDown() {

        digester = null;

    }



    // ------------------------------------------------ Individual Test Methods


    /**
     * Test object creation (and associated property setting) with nothing on
     * the stack, which should cause an appropriate Employee object to be
     * returned.
     */
    public void testObjectCreate1() {

        // Configure the digester as required
        digester.addObjectCreate("employee",
                                 "org.apache.commons.digester.Employee");
        digester.addSetProperties("employee");

        // Parse our test input.
        Object root = null;
        try {
            root = digester.parse(getInputStream("Test1.xml"));
        } catch (Throwable t) {
            fail("Digester threw IOException: " + t);
        }
        //  测试非空
        assertNotNull("Digester returned an object", root);
        // 测试栈顶的元素时候Employee或者时候他的子类型
        assertTrue("Digester returned an Employee",
                   root instanceof Employee);
        Employee employee = (Employee) root;
        
        // 测试firstName和lastName有没有被正确的设置
        assertEquals("First name is correct",
                     "First Name",
                     employee.getFirstName());
        assertEquals("Last name is correct",
                     "Last Name",
                     employee.getLastName());


    }


    /**
     * Test object creation (and associated property setting) with nothing on
     * the stack, which should cause an appropriate Employee object to be
     * returned.  The processing rules will process the nested Address elements
     * as well, but will not attempt to add them to the Employee.
     */
    public void testObjectCreate2() {

        // Configure the digester as required
        digester.addObjectCreate("employee",
                                 "org.apache.commons.digester.Employee");
        digester.addSetProperties("employee");
        digester.addObjectCreate("employee/address",
                                 "org.apache.commons.digester.Address");
        digester.addSetProperties("employee/address");

        // Parse our test input.
        Object root = null;
        try {
            root = digester.parse(getInputStream("Test1.xml"));
        } catch (Throwable t) {
            fail("Digester threw IOException: " + t);
        }
        // 测试非空
        assertNotNull("Digester returned an object", root);
        
        // 测试栈顶的元素是不是Employee或者是它的子类
        assertTrue("Digester returned an Employee",
                   root instanceof Employee);
        
        // 测试firstName和lastName有没有被正确设置
        Employee employee = (Employee) root;
        assertEquals("First name is correct",
                     "First Name",
                     employee.getFirstName());
        assertEquals("Last name is correct",
                     "Last Name",
                     employee.getLastName());


    }


    /**
     * Test object creation (and associated property setting) with nothing on
     * the stack, which should cause an appropriate Employee object to be
     * returned.  The processing rules will process the nested Address elements
     * as well, and will add them to the owning Employee.
     */
    public void testObjectCreate3() {

        // Configure the digester as required
        digester.addObjectCreate("employee",
                                 "org.apache.commons.digester.Employee");
        digester.addSetProperties("employee");
        digester.addObjectCreate("employee/address",
                                 "org.apache.commons.digester.Address");
        digester.addSetProperties("employee/address");
        digester.addSetNext("employee/address",
                            "addAddress");

        // Parse our test input once
        Object root = null;
        try {
            root = digester.parse(getInputStream("Test1.xml"));
        } catch (Throwable t) {
            fail("Digester threw IOException: " + t);
        }
        validateObjectCreate3(root);

        // Parse the same input again
        try {
            root = digester.parse(getInputStream("Test1.xml"));
        } catch (Throwable t) {
            fail("Digester threw IOException: " + t);
        }
        validateObjectCreate3(root);

    }


    /**
     * Same as testObjectCreate1(), except use individual call method rules
     * to set the properties of the Employee.
     */
    public void testObjectCreate4() {

        // Configure the digester as required
        digester.addObjectCreate("employee",
                                 "org.apache.commons.digester.Employee");
        digester.addCallMethod("employee",
                               "setFirstName", 1);
        digester.addCallParam("employee", 0, "firstName");
        digester.addCallMethod("employee",
                               "setLastName", 1);
        digester.addCallParam("employee", 0, "lastName");


        // Parse our test input.
        Object root = null;
        try {
            root = digester.parse(getInputStream("Test1.xml"));
        } catch (Throwable t) {
            fail("Digester threw IOException: " + t);
        }
        // 测试非空和类型检验
        assertNotNull("Digester returned an object", root);
        assertTrue("Digester returned an Employee",
                   root instanceof Employee);
        
        // 测试了CallMethodRule和CallParamRule没有能被正确调用
        Employee employee = (Employee) root;
        assertEquals("First name is correct",
                     "First Name",
                     employee.getFirstName());
        assertEquals("Last name is correct",
                     "Last Name",
                     employee.getLastName());


    }


    /**
     * It should be possible to parse the same input twice, and get trees
     * of objects that are isomorphic but not be identical object instances.
     */
    public void testRepeatedParse() {
    	// 这个主要时候测试重复的parse后生成的元素时候不同的。

        // Configure the digester as required
        digester.addObjectCreate("employee",
                                 "org.apache.commons.digester.Employee");
        digester.addSetProperties("employee");
        digester.addObjectCreate("employee/address",
                                 "org.apache.commons.digester.Address");
        digester.addSetProperties("employee/address");
        digester.addSetNext("employee/address",
                            "addAddress");

        // Parse our test input the first time
        Object root1 = null;
        try {
            root1 = digester.parse(getInputStream("Test1.xml"));
        } catch (Throwable t) {
            fail("Digester #1 threw Exception:  " + t);
        }
        validateObjectCreate3(root1);

        // Parse our test input the second time
        Object root2 = null;
        try {
            root2 = digester.parse(getInputStream("Test1.xml"));
        } catch (Throwable t) {
            fail("Digester #2 threw Exception:  " + t);
        }
        validateObjectCreate3(root2);

        // Make sure that it was a different root
        assertTrue("Different tree instances were returned",
                   root1 != root2);

    }


    /**
     * Test object creation (and associated property setting) with nothing on
     * the stack, which should cause an appropriate Employee object to be
     * returned.  The processing rules will process the nested Address elements
     * as well, but will not attempt to add them to the Employee.
     */
    public void testRuleSet1() {

        // Configure the digester as required
        RuleSet rs = new TestRuleSet();
        digester.addRuleSet(rs);

        // Parse our test input.
        Object root = null;
        try {
            root = digester.parse(getInputStream("Test1.xml"));
        } catch (Throwable t) {
            fail("Digester threw IOException: " + t);
        }

        // 主要时候测试使用RuleSet时候Rule能被正确的解析和执行
        assertNotNull("Digester returned an object", root);
        assertTrue("Digester returned an Employee",
                   root instanceof Employee);
        Employee employee = (Employee) root;
        assertEquals("First name is correct",
                     "First Name",
                     employee.getFirstName());
        assertEquals("Last name is correct",
                     "Last Name",
                     employee.getLastName());
        assertNotNull("Can retrieve home address",
                      employee.getAddress("home"));
        assertNotNull("Can retrieve office address",
                      employee.getAddress("office"));

    }


    /**
     * Same as <code>testRuleSet1</code> except using a single namespace.
     */
    public void testRuleSet2() {

        // Configure the digester as required
        digester.setNamespaceAware(true);
        RuleSet rs = new TestRuleSet(null,
                                     "http://jakarta.apache.org/digester/Foo");
        digester.addRuleSet(rs);

        // Parse our test input.
        Object root = null;
        try {
            root = digester.parse(getInputStream("Test2.xml"));
        } catch (Throwable t) {
            fail("Digester threw IOException: " + t);
        }

        assertNotNull("Digester returned an object", root);
        assertTrue("Digester returned an Employee",
                   root instanceof Employee);
        Employee employee = (Employee) root;
        assertEquals("First name is correct",
                     "First Name",
                     employee.getFirstName());
        assertEquals("Last name is correct",
                     "Last Name",
                     employee.getLastName());
        assertNotNull("Can retrieve home address",
                      employee.getAddress("home"));
        assertNotNull("Can retrieve office address",
                      employee.getAddress("office"));

    }


    /**
     * Same as <code>testRuleSet2</code> except using a namespace
     * for employee that we should recognize, and a namespace for
     * address that we should skip.
     */
    public void testRuleSet3() {

        // Configure the digester as required
        digester.setNamespaceAware(true);
        RuleSet rs = new TestRuleSet(null,
                                     "http://jakarta.apache.org/digester/Foo");
        digester.addRuleSet(rs);

        // Parse our test input.
        Object root = null;
        try {
            root = digester.parse(getInputStream("Test3.xml"));
        } catch (Throwable t) {
            fail("Digester threw IOException: " + t);
        }

        assertNotNull("Digester returned an object", root);
        assertTrue("Digester returned an Employee",
                   root instanceof Employee);
        Employee employee = (Employee) root;
        assertEquals("First name is correct",
                     "First Name",
                     employee.getFirstName());
        assertEquals("Last name is correct",
                     "Last Name",
                     employee.getLastName());
        
        // 这个主要时候测试把namespaceURL不添加到上面,其实通过这个testcase我们
        // 可以看到RuleSet里面的namespaceURI的作用了,它会给加到他里面的所有的
        // rule都加上这个namespaceURI,然后将这个namespaceURI应用到所有的rule
        // 上面,在获得rule的时候只会得到相匹配的rule,起到一个过滤功能
        assertNull("Can not retrieve home address",
                   employee.getAddress("home"));
        assertNull("Can not retrieve office address",
                   employee.getAddress("office"));

    }


    // ------------------------------------------------ Utility Support Methods


    /**
     * Return an appropriate InputStream for the specified test file (which
     * must be inside our current package.
     *
     * @param name Name of the test file we want
     *
     * @exception IOException if an input/output error occurs
     */
    protected InputStream getInputStream(String name) throws IOException {

        return (this.getClass().getResourceAsStream
                ("/org/apache/commons/digester/" + name));

    }


    /**
     * Validate the assertions for ObjectCreateRule3.
     *
     * @param object Root object returned by <code>digester.parse()</code>
     */
    protected void validateObjectCreate3(Object root) {

    	// 检验Employee的信息
        // Validate the retrieved Employee
        assertNotNull("Digester returned an object", root);
        assertTrue("Digester returned an Employee",
                   root instanceof Employee);
        Employee employee = (Employee) root;
        assertEquals("First name is correct",
                     "First Name",
                     employee.getFirstName());
        assertEquals("Last name is correct",
                     "Last Name",
                     employee.getLastName());

        // 检验名称时候home的address元素的相关属性
        // Validate the corresponding "home" Address
        Address home = employee.getAddress("home");
        assertNotNull("Retrieved home address", home);
        assertEquals("Home street", "Home Street",
                     home.getStreet());
        assertEquals("Home city", "Home City",
                     home.getCity());
        assertEquals("Home state", "HS",
                     home.getState());
        assertEquals("Home zip", "HmZip",
                     home.getZipCode());

        // 检验名称叫office的address的相关属性
        // Validate the corresponding "office" Address
        Address office = employee.getAddress("office");
        assertNotNull("Retrieved office address", office);
        assertEquals("Office street", "Office Street",
                     office.getStreet());
        assertEquals("Office city", "Office City",
                     office.getCity());
        assertEquals("Office state", "OS",
                     office.getState());
        assertEquals("Office zip", "OfZip",
                     office.getZipCode());

    }


}

分享到:
评论

相关推荐

    digester用法测试案例

    Digester是Apache软件基金会的Jakarta项目中的一个实用工具库,它主要用来解析XML文档,并根据预定义的规则自动创建和配置Java对象。这个工具在处理XML到Java对象映射时,极大地简化了代码,避免了手动解析XML的繁琐...

    XML的解析之——使用Digester

    本文将深入探讨如何使用Apache的 Digester 库来解析XML文档,这是一款强大的工具,能够将XML数据映射到Java对象,简化了处理XML的过程。 Digester 是Apache Commons项目的一部分,它提供了一种规则驱动的方法来处理...

    commons-digester3-3.2-API文档-中英对照版.zip

    赠送jar包:commons-digester3-3.2.jar; 赠送原API文档:commons-digester3-3.2-javadoc.jar; 赠送源代码:commons-digester3-3.2-sources.jar; 赠送Maven依赖信息文件:commons-digester3-3.2.pom; 包含翻译后...

    Digester

    Digester是Apache软件基金会下的Jakarta项目中的一个Java库,主要用于简化XML到Java对象的映射过程。在处理XML文档时,它通过匹配XML元素结构到相应的Java对象的方法调用,实现了XML解析的自动化。这个工具对于那些...

    commons-digester.jar

    `commons-digester.jar`是Apache Commons项目中的一个组件,主要功能是解析XML文档并根据预定义的规则自动创建和填充Java对象。这个组件在Java应用程序中尤其有用,特别是那些需要从XML配置文件中构建复杂对象层次...

    Castor、digester实例

    Castor和Digester是两个在Java开发中用于对象与XML数据之间进行映射的库,它们简化了XML数据的解析和对象的序列化过程。在本文中,我们将深入探讨这两个库,以及如何通过实例来使用它们。 首先,让我们了解Castor。...

    commons-digester-2.1.jar

    `commons-digester-2.1.jar` 是Apache Commons项目中的一个组件,主要负责XML文档的解析和对象的创建与绑定。Apache Commons Digester库提供了一种规则驱动的方法来解析XML文档,并根据预定义的规则将XML数据映射到...

    Digester java解析xml

    Java中的Digester库是Apache Commons项目的一部分,它提供了一种方便的方式来解析XML文档,并将解析结果映射到Java对象模型上。这个库特别适合于创建简单的XML到Java对象的映射,而不需要编写大量的手动解析代码。在...

    利用commons-digester解析xml

    标题“利用commons-digester解析XML”涉及到的是Java开发中的一种处理XML文档的工具——Apache Commons Digester。这个库提供了一种方便的方式来映射XML文档结构到Java对象,从而简化了XML数据的处理过程。 Apache ...

    digester使用

    《digester深度解析》 Java世界中,XML作为数据交换和配置文件的常用格式,其解析和对象绑定是一项常见的任务。Apache Commons Digester是Apache软件基金会提供的一个强大的工具,专门用于将XML文档解析为Java对象...

    Java_XML解析之Digester的使用

    Java XML解析中的Digester是一个强大的工具,用于将XML文档转换为Java对象。它最初是为了处理Struts框架的配置文件而设计的,随着时间的发展,它成为一个轻量级且高效的框架,专注于单向转换,即从XML到Java对象。...

    Digester读取xml教程.rar

    《使用Digester解析XML的深度指南》 在Java开发中,处理XML文件是常见的任务,而Apache Commons Digester库提供了一种高效且便捷的方式来解析XML并将其映射到Java对象。本教程将深入探讨如何使用Digester来读取XML...

    digester组件简化了xml文件处理操作

    ### Digester组件简化XML文件处理操作 #### 一、引言 随着Web技术的发展,XML作为数据交换格式的重要性日益凸显。然而,对于大型且复杂的XML文档进行解析与处理时,传统的方法如DOM(Document Object Model)和SAX...

    Digester两种解析方式

    在Java开发中,Apache Commons Digester是一个非常有用的库,它允许开发者通过XML配置来实例化、配置和关联Java对象。 Digester提供了两种主要的解析方式,即规则硬编码和独立的规则文件,这两种方法各有其特点和...

    commons-digester3-3.2-API文档-中文版.zip

    赠送jar包:commons-digester3-3.2.jar; 赠送原API文档:commons-digester3-3.2-javadoc.jar; 赠送源代码:commons-digester3-3.2-sources.jar; 赠送Maven依赖信息文件:commons-digester3-3.2.pom; 包含翻译后...

    自动化单元测试框架NUnit的改进设计与实现.pdf

    NUnit是一个开源的单元测试框架,它针对.NET环境下的软件项目提供了自动化测试的支持。NUnit框架的设计目标是提高开发者编写测试代码的效率,确保代码质量和功能正确性。 在自动化测试框架的发展过程中,NUnit借鉴...

    Digester解析XML的小例子(对象嵌套)

    在Java开发中,Struts框架提供了一个强大的工具——Digester,用于解析XML文件并自动创建、配置Java对象。本文将详细介绍如何使用Digester处理具有嵌套结构的XML文档,并通过一个具体的实例——"DigesterXmlTest"来...

    digester解析xml的问题.pdf

    Digester 是 Apache Commons 中的一个工具类库,它用于解析 XML 文档,并根据预先定义的规则自动创建和配置 Java 对象。在上述问题中,我们看到一个 XML 文档表示了一个考试,其中包含了多个题目,每个题目有其编号...

    用到digester项目,直接解析存入数据库

    标题中的“用到digester项目,直接解析存入数据库”指的是使用Apache Digester库来解析XML文件,并将解析后的数据直接存储到数据库中。Apache Digester是一个Java库,它允许开发者通过规则配置来关联XML文档的元素与...

    org.apache.commons.digester解析XML.rar

    这个“org.apache.commons.digester解析XML.rar”压缩包包含了一个测试工程,它演示了如何使用Digester库来解析XML文件并映射到Java对象上。下面将详细介绍这个库的功能、使用方法以及在实际开发中的应用。 1. **...

Global site tag (gtag.js) - Google Analytics