gpt4 book ai didi

java - 如何编写 JUnit 测试用例来查找流中的第一个非重复字符?

转载 作者:行者123 更新时间:2023-12-02 01:11:50 25 4
gpt4 key购买 nike

由于用户更关注小漏洞而不是需求,因此我给出了我需要 junit 测试用例的实际工作代码(替换)。

import java.util.*;

public class FirstNonRepeatingCharacterStream {

List<Character> chars = new ArrayList<>();
boolean[] repeated = new boolean[256];

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
FirstNonRepeatingCharacterStream tester =
new FirstNonRepeatingCharacterStream();
while (true) {
Character ch = new Character(sc.next().charAt(0));
Character output = tester.firstNonRepeatingCharStream1(ch);
System.out.println(output);
}
}

public Character firstNonRepeatingCharStream1(Character x) {

if (x == null) {
return x;
}

Character output = null;

if (!repeated[x]) {
if (!chars.contains(x)) {
chars.add(x);
} else {
chars.remove(new Character(x));
repeated[x] = true;
}
}
if (chars.size() != 0) {
output = new Character(chars.get(0));
}
return output;

}

}

User enters one character at a time.
input a -> output a
input b -> that means input ab as it's stream -> output a
input a -> that means input aba as it's stream -> output b
input c -> that means input abac as it's stream -> output b
input b -> that means input abacb as it's stream -> output c
input a -> that means input abacba as it's stream -> output c
input d -> that means input abacbad as it's stream -> output c

请告诉我如何编写符合main方法的单元测试。 junit 测试用例中不需要有 while 循环。

提前致谢。

最佳答案

这听起来主要归结为提出“平均”测试字符串来尝试击中代码中的各种边缘情况:

String testStrings[] {
null,
"", // empty string
"a", // easiest possible string with a match
"aa", // easiest possible string with no match
"aba", // slightly less easy string with a match
"aaaaa", // no match on N instances of a character
"aaaaab", // match on end of N instances of a character
"baaaaa", // match at beginning of N instances of a character
"aabaaa", // match in the middle of N instances of a character
"abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba", // harder string where the unique letter is in the middle (z)
"abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcb", // harder string where the unique character is at the front (a)
"bcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba", // harder string where the unique character is at the back
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy" // other harder string... etc.
};

然后,您开发一个类似的预期输出数组,然后在一个 for(int i = 0;...) 循环中快速处理所有情况。

开发测试输入的另一种方法是通过算法生成测试字符串,使得所有字符在三种策略(aabbcc、abccba、abcabc)之一中成对出现,然后取出第一个字符,然后取出最后一个字符,然后是中间的一个(您检查要先删除哪个字符,这将成为您的测试值)。

有很多不同的方法可以给这只猫剥皮。

PS:您当前的代码将因 null 或任何“整数”值大于 255 的字符而中断。那里有很多奇怪的 Unicode 字符...我似乎记得听说过有几个死了虚构语言现在采用 Unicode(古埃及语、JJR Tolkien 的 Sprite 语、克林贡语等),更不用说 CJKV 范围(中文、日语、韩语、越南语)了。 256 之外还有很多“代码点”。

关于java - 如何编写 JUnit 测试用例来查找流中的第一个非重复字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57681824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com