jvm 在运行时,我在junit测试和Android(ART)上对相同的输入得到了不同的结果

gxwragnw  于 2022-11-07  发布在  Android
关注(0)|答案(1)|浏览(100)

我有一个静态方法,它在目标文本上找到匹配的文本,但它对相同的输入返回不同的结果,Junit测试中的结果和Android运行时的结果是不同的。

private const val REGEX = "GE[a-zA-Z0-9]{2}\\s?([a-zA-Z0-9]{2})([0-9]{2}\\s?)([0-9]{4}\\s?){3}([0-9]{2})\\s?"
private val PATTERN: Pattern = Pattern.compile(REGEX, Pattern.MULTILINE or Pattern.CASE_INSENSITIVE)

fun find(text: String): List<String> {
    val textFormatted = text.replace("\\s".toRegex(), "")
    val list = ArrayList<String>()
    val matcher = matcher(textFormatted)
    when {
        matcher.matches() -> {
            list.add(textFormatted)
        }
        matcher.find() -> {
            val partitions = findGroupMatches(matcher)
            list.addAll(partitions)
        }
    }
    return list
}

private fun findGroupMatches(matcher: Matcher): List<String> {
    val partitions = mutableListOf<String>()
    for (i in 0 until matcher.groupCount()) {
        val partition = matcher.group(i)
        if (partition != null && PATTERN.matcher(partition).matches()) {
            partitions.add(partition.replace("\\s".toRegex(), ""))
        }
    }
    return partitions
}

神奇的事情就发生在这里

On JVM tests, it returns emptyList

@Test
fun `find with not valid text returns emptyList`(){
    val targets = PatternUtils.find("GE03TB 7433311450666666300008")
    assertTrue(targets.isEmpty()) // success
}

PatternUtils.find("GE03TB 7433311450666666300008") on Android inside `onCreate()` returns 1 size list("GE03TB743331145066666") //

为什么会这样?有什么问题吗?还是我漏掉了什么?

35g0bw71

35g0bw711#

原因是Oracle和Google的Pattern.java实现不同。
为了能以类似的方式工作,我不得不创建新的Matcher,而不是重用它。(Matcher.java有一些方法会产生副作用)

fun find(text: String): List<String> {
    val textFormatted = text.replace("\\s".toRegex(), "")
    val list = ArrayList<String>()
    val matcher = createMatcher(textFormatted)
    when {
        createMatcher(textFormatted).matches() -> {
            list.add(textFormatted)
        }
        matcher.find() -> {
            val partitions = findGroupMatches(matcher)
            list.addAll(partitions)
        }
    }
    return list
}

相关问题