我有一个简单的 JSON 词法分析器类;它需要 astring
并生成一个IJSONValue
; 有IJSONValue
一个ToJSONString
返回有效 JSON 字符串的方法。
当然,它的代码非常复杂,有很多分支。这就是为什么我认为这将是测试 Pex 能力的理想场所。我创建了以下测试:
[TestClass]
[PexClass]
public partial class JSONTests {
[PexGenericArguments(typeof(JSONArray))]
[PexGenericArguments(typeof(JSONBoolean))]
[PexGenericArguments(typeof(JSONNull))]
[PexGenericArguments(typeof(JSONNumber))]
[PexGenericArguments(typeof(JSONObject))]
[PexGenericArguments(typeof(JSONString))]
[PexMethod]
public void TestLexer<T>([PexAssumeNotNull] T value) where T : IJSONValue {
string json = value.ToJSONString();
IJSONValue result = new JSONLexer().GetValue(json);
PexAssert.AreEqual(value, result);
}
}
在此运行 Pex,我发现了一些与 null 处理无关的问题,我已经修复了这些问题。但是,我也有很多方法报告没有意义的异常。它们看起来像这样:
[TestMethod]
[PexGeneratedBy(typeof(JSONTests))]
[PexRaisedException(typeof(JSONException))]
public void TestLexerThrowsJSONException78() {
JSONBoolean s0 = new JSONBoolean(true);
this.TestLexer<JSONBoolean>(s0);
}
然而,这与我知道有效的测试之一非常相似。我在调试器中和调试器外部运行它,在这两种情况下测试都通过了。最令人难以置信的是,异常文本实际上是有道理的;Constant
如果正则表达式与字符串不匹配,则会报告该文本"false"
。对于其他正则表达式不匹配,我得到了类似的例外,这是没有意义的。
为什么 Pex 认为这会引发异常?仪器是否混乱ThreadLocal
或Regex
以一种奇怪的方式?这就是我的正则表达式持有类的样子(为简洁起见,对正则表达式进行了编辑)。
private static class Regexes {
private static RegexOptions Options = RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace;
public static ThreadLocal<Regex> String = new ThreadLocal<Regex>(() => new Regex(@"(...)", Options));
public static ThreadLocal<Regex> Number = new ThreadLocal<Regex>(() => new Regex(@"(...)", Options));
public static ThreadLocal<Regex> Constant = new ThreadLocal<Regex>(() => new Regex(@"(...)", Options));
}