用Java测试平面文件内容和格式

时间:2015-06-04 15:09:43

标签: java unit-testing

我必须将一个平面文件发送到外部系统。示例文件内容如下:

START 20150602
HEADER 100.00USD
PRODUCT TEST1                    50.00USD
PRODUCT TEST2                    50.00USD
FOOTER 002

此文件应遵循以下准则:

First line - starts with START, then space, then today's date in YYYYMMDD
Header line - starts with HEADER, then space, then total amount of first, second, third etc products with 2 decimal points, then currency
First product - starts with PRODUCT, then space, then product name left aligned with total 25 characters, then amount with 2 decimal points, then currency
More products similar to first product, the number of products is dynamic
Footer - starts with FOOTER, then space, then total number of products with 3 digits

这种格式由外部系统供应商在excel中提供。

在这种情况下,你们中的任何人都可以提出更好的测试策略吗?有没有工具来测试文件内容和格式?

1 个答案:

答案 0 :(得分:1)

在这种情况下,我更倾向于从基于Java基本功能的简单方法开始探索我的选择。这里,每一行可以用正则表达式来描述:

START (\d{8})
HEADER (\d+\.\d{2})(\w{3})
PRODUCT (.{25}) (\d+\.\d{2})(\w{3})
FOOTER (\d{3})

如果您不需要提取和检查值,则可能不需要括号。 OTOH,添加一个字符串列表,为这些字段提供名称,以便将它们输入到地图中。

您可以为每一行添加最小和最大重复次数,这样您就可以编写一些简单的逻辑来迭代文件的行。

这些可能是工厂方法调用,其中所有上述内容都定义为几行:

LineDef.create( "HEADER (\\d+\\.\\d{2})(\\w{3})", 1, 1,
                "totalAmount", "totalCurrency" ); 
LineDef.create( "PRODUCT (.{25}) (\\d+\\.\\d{2})(\\w{3})", 1, 999,
               "name", "amount", "currency" );