如何在Visual Studio Code中编写单元测试验证XML与XSD Schema?
在VS Code中编写单元测试验证XML与XSD一致性
现有文件内容
taller1.xsd(Schema定义文件)
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="profesor" type="Profesor_Atributos"/> <xs:complexType name="Profesor_Atributos"> <xs:sequence> <xs:element name="id" type="xs:string" minOccurs="1" maxOccurs="1" /> <xs:element name="nombre" type="xs:string" minOccurs="1" maxOccurs="1" /> <xs:element name="apellido" type="xs:string" minOccurs="1" maxOccurs="1" /> <xs:element name="edad" type="xs:integer" minOccurs="1" maxOccurs="1"/> </xs:sequence> </xs:complexType> </xs:schema>
taller1.xml(待验证的XML文件)
<?xml version="1.0" encoding="ISO-8859-1"?> <profesor xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="taller1.xsd" > <id>a1</id> <nombre>Juan</nombre> <apellido>Pedro</apellido> <edad>30</edad> </profesor>
单元测试实现步骤
1. 搭建测试环境
在项目根目录执行以下命令初始化Node.js项目并安装依赖:
npm init -y npm install --save-dev jest xmlschema
2. 编写测试代码
在项目中创建test/xml-validation.test.js文件,内容如下:
const { XMLSchema } = require('xmlschema'); const fs = require('fs'); const path = require('path'); describe('XML Schema 验证', () => { let schema; let xmlContent; // 测试前加载Schema和XML文件 beforeAll(() => { // 读取XSD Schema const xsdFilePath = path.join(__dirname, '../taller1.xsd'); const xsdContent = fs.readFileSync(xsdFilePath, 'utf8'); schema = new XMLSchema(xsdContent); // 读取XML(注意编码为ISO-8859-1,对应Node.js的latin1编码) const xmlFilePath = path.join(__dirname, '../taller1.xml'); xmlContent = fs.readFileSync(xmlFilePath, 'latin1'); }); test('taller1.xml 完全符合 taller1.xsd 规范', () => { const validationResult = schema.validate(xmlContent); // 断言验证结果为有效 expect(validationResult.valid).toBe(true); // 若验证失败,打印错误详情 if (!validationResult.valid) { console.error('验证错误信息:', validationResult.errors); } }); });
3. 配置测试脚本
在package.json中添加测试命令:
{ "scripts": { "test": "jest" } }
4. 运行测试
在VS Code终端执行以下命令启动测试:
npm test
如果XML符合Schema规范,测试会通过;若存在不符合的地方,终端会输出具体的错误信息。
内容的提问来源于stack exchange,提问作者Mario Ortiz
相关产品推荐
相关产品推荐

