Java TestNG中如何将System.lineSeparator()作为常量解决注解属性报错
TestNG注解expectedExceptionsMessageRegExp属性常量报错问题解答
错误成因
- Java 注解的所有属性值必须是编译期可确定的常量:注解作为类、方法的元数据,会在编译阶段直接写入Class文件,不允许赋值为运行时才能计算得到的动态值。
System.lineSeparator()是运行时根据当前操作系统环境返回对应换行符(Windows返回\r\n、类Unix返回\n)的方法,其返回值不属于编译期常量,和静态字符串拼接后的整体结果也不符合常量要求,因此触发编译错误。
解决方案
方案1(推荐):利用正则特性适配任意换行符
expectedExceptionsMessageRegExp属性本身接收的是正则表达式模式,你可以直接使用正则语法中的\R匹配任意系统的换行符,无需动态拼接:
@Test(description = "When path parameter has given unmatch data type in ballerina", expectedExceptions = BallerinaOpenApiException.class, expectedExceptionsMessageRegExp = "File has errors: \\RSemicolon is missing at line 45") public void testMissionSemicolon() throws IOException, BallerinaOpenApiException { // test implementation }
注:Java字符串中反斜杠需要转义,因此正则的
\R要写为\\R,如果需要兼容可能存在的多个换行/空白符,可以调整为\\R+。
方案2:使用编译期常量换行符
如果你的测试运行环境固定,直接使用编译期可识别的转义换行符即可:
// 适配类Unix环境写\n,适配Windows写\r\n expectedExceptionsMessageRegExp = "File has errors: \nSemicolon is missing at line 45"
方案3:手动捕获异常做断言
如果需要完全兼容运行时动态生成的匹配规则,可以放弃注解的异常校验属性,改用try-catch手动捕获后校验:
@Test(description = "When path parameter has given unmatch data type in ballerina") public void testMissionSemicolon() throws IOException { try { // 原测试实现代码 Assert.fail("未抛出预期异常"); } catch (BallerinaOpenApiException e) { String expectedMsg = "File has errors: " + System.lineSeparator() + "Semicolon is missing at line 45"; Assert.assertEquals(e.getMessage(), expectedMsg); } }
内容的提问来源于stack exchange,提问作者Aneesha Fernando
相关产品推荐
相关产品推荐

