You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java reverseWord方法JUnit测试失败 如何编写正确测试用例

原功能代码存在的问题
  • 核心逻辑错误:方法仅将反转后的单词序列打印到控制台,最终返回值仍是未修改的原输入字符串str,这是测试断言失败的直接原因。
  • 拼接结果存在冗余空格:循环中每次拼接a[i] + " ",最终生成的字符串末尾会多一个多余空格,即使存储拼接结果也会和预期值不匹配。
  • 无效异常捕获:split方法不会因正常输入抛出异常,此处try-catch属于冗余代码,无实际作用。
  • 空格分割逻辑鲁棒性差:使用split(" ")仅能匹配单个空格,若输入存在连续空格、开头/结尾带空格的场景,会生成空字符串元素,导致反转结果不符合预期。
修正后的功能代码
public static String reverseWord(String str) {
    // 先去除首尾空格,再用任意长度空白字符分割
    String[] words = str.trim().split("\\s+");
    StringBuilder reversed = new StringBuilder();
    for (int i = words.length - 1; i >= 0; i--) {
        reversed.append(words[i]);
        // 最后一个单词后不拼接空格
        if (i != 0) {
            reversed.append(" ");
        }
    }
    return reversed.toString();
}
正确的JUnit测试用例编写

测试用例需要覆盖所有常见边界场景,示例如下:

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class LogicTest {
    // 常规多单词场景
    @Test
    public void testReverseNormalWords() {
        assertEquals("world hello", Logic.reverseWord("hello world"));
    }

    // 单个单词场景
    @Test
    public void testReverseSingleWord() {
        assertEquals("test", Logic.reverseWord("test"));
    }

    // 带首尾空格的场景
    @Test
    public void testReverseWithSurroundSpace() {
        assertEquals("java hello", Logic.reverseWord("  hello java  "));
    }

    // 带连续空格的场景
    @Test
    public void testReverseWithContinuousSpace() {
        assertEquals("code write to love I", Logic.reverseWord("I love  to   write code"));
    }

    // 空字符串/全空格场景
    @Test
    public void testReverseEmptyInput() {
        assertEquals("", Logic.reverseWord(""));
        assertEquals("", Logic.reverseWord("   "));
    }
}

不修改原功能代码、仅调整测试用例匹配现有逻辑没有实际意义,因为原方法本身的返回值不符合单词反转的需求。

内容的提问来源于stack exchange,提问作者kunal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:30:04