如何测试 LinkedHashMap 的值和键?

huangapple go评论71阅读模式
英文:

How to test values and keys of LinkedHashMap?

问题

我编写了一个方法,将字符串的字符放入LinkedHashMap中作为键,字符的数量作为值,但我不知道如何测试这个方法是否正确计算字符。

LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < string.length(); i++) {
    char wordToLetter = string.toLowerCase().charAt(i);
    if (map.containsKey(wordToLetter)) {
        int quantity = map.get(wordToLetter);
        map.put(wordToLetter, ++quantity);
    } else {
        map.put(wordToLetter, 1);
    }
}
return map;

输入示例: "abc de"

作为测试,我想检查是否有一个字符"a",其正确的数量为1。

英文:

I wrote method which put chars of a string into LinkedHashMap as a key and quantity of that chars as value, but I don't know how can I test if this method properly count chars.

LinkedHashMap&lt;Character, Integer&gt; map = new LinkedHashMap&lt;&gt;();
for (int i = 0; i &lt; string.length(); i++) {
    char wordToLetter = string.toLowerCase().charAt(i);
    if (map.containsKey(wordToLetter)) {
        int quantity = map.get(wordToLetter);
        map.put(wordToLetter, ++quantity);
    } else {
        map.put(wordToLetter, 1);
    }
}
return map;

Example of input : "abc de"

and as test I want to check if I have a char "a" with proper quantity 1.

答案1

得分: 1

这是您的测试示例:

这里是您的代码示例
```java

<details>
<summary>英文:</summary>

here is the test example for your case:

    package your.package.here;
    
    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.collection.IsMapContaining.hasEntry;
    
    import java.util.Map;
    import org.junit.Test;
    
    public class MainTest {
    
      @Test
      public void testMapContent() {
        String input = &quot;abc de&quot;;
        Integer aExpectedCount = 1;
    
        Map&lt;Character, Integer&gt; generatedMap = Main.generateMap(input);
    
        assertThat(generatedMap, hasEntry(&#39;a&#39;, aExpectedCount));
      }
    }

and the Main class:

    package your.package.here;
    
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    public class Main {  
    
      public static Map&lt;Character, Integer&gt; generateMap(String string) {
        LinkedHashMap&lt;Character, Integer&gt; map = new LinkedHashMap&lt;&gt;();
        for (int i = 0; i &lt; string.length(); i++) {
          char wordToLetter = string.toLowerCase().charAt(i);
          if (map.containsKey(wordToLetter)) {
            int quantity = map.get(wordToLetter);
            map.put(wordToLetter, ++quantity);
          } else {
            map.put(wordToLetter, 1);
          }
        }
        return map;
      }
    }





</details>



# 答案2
**得分**: 1

以下是测试的方法

```java
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<Character, Integer> charCountMap = output("abc de");
        assertEquals(1, charCountMap.get('a'));
        assertEquals(1, charCountMap.get('b'));
        assertEquals(1, charCountMap.get(' '));
    }

    public static LinkedHashMap<Character, Integer> output(String inputString) {
        LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
        for (int i = 0; i < inputString.length(); i++) {
            char wordToLetter = inputString.toLowerCase().charAt(i);
            if (map.containsKey(wordToLetter)) {
                int quantity = map.get(wordToLetter);
                map.put(wordToLetter, ++quantity);
            } else {
                map.put(wordToLetter, 1);
            }
        }
        return map;
    }
}
如果你将不同的值放入例如 `assertEquals(2, charCountMap.get('a'));`,它将抛出 `AssertionFailedError` 异常
英文:

Given below is a way to test it:

import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) {
LinkedHashMap&lt;Character, Integer&gt; charCountMap = output(&quot;abc de&quot;);
assertEquals(1, charCountMap.get(&#39;a&#39;));
assertEquals(1, charCountMap.get(&#39;b&#39;));
assertEquals(1, charCountMap.get(&#39; &#39;));
}
public static LinkedHashMap&lt;Character, Integer&gt; output(String inputString) {
LinkedHashMap&lt;Character, Integer&gt; map = new LinkedHashMap&lt;&gt;();
for (int i = 0; i &lt; inputString.length(); i++) {
char wordToLetter = inputString.toLowerCase().charAt(i);
if (map.containsKey(wordToLetter)) {
int quantity = map.get(wordToLetter);
map.put(wordToLetter, ++quantity);
} else {
map.put(wordToLetter, 1);
}
}
return map;
}
}

If you put a different value e.g. assertEquals(2, charCountMap.get(&#39;a&#39;));, it will throw AssertionFailedError exception.

答案3

得分: 0

这是一个测试字符的方法。它不使用 Junit,但可以很容易地进行调整。

Random r = new Random();
// 保存种子以便后面重复测试
long seed = r.nextLong();
r.setSeed(seed);

// 供应商以获取介于 5 到 14 个字符之间的字母计数
Supplier<Integer> rnd = () -> r.nextInt(10) + 5;

现在使用一组字母生成测试字符串。

String letters = "abcdefg";
// 这只是连接了不同长度的测试字符
String testString = letters.chars()
    .mapToObj(ch -> ((char) ch + "").repeat(rnd.get()))
    .collect(Collectors.joining(""));

现在调用您的方法以执行计数。

Map<Character, Integer> freq = countChars(testString);

现在进行测试。重新设置随机数种子,并将已知字母计数与计算得到的计数进行比较。

r.setSeed(seed);
for (char ch : letters.toCharArray()) {
    System.out.printf("Count for '%s' %s%n", ch,
            (freq.get(ch) == rnd.get()) ? "passes" :
                    "does not pass");
}

对于计数方法,它打印出

Count for 'a' passes
Count for 'b' passes
Count for 'c' passes
Count for 'd' passes
Count for 'e' passes
Count for 'f' passes
Count for 'g' passes

您的代码放在一个方法中。

public static Map<Character, Integer> countChars(String string) {
    LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
    for (int i = 0; i < string.length(); i++) {
        char wordToLetter = string.toLowerCase().charAt(i);
        if (map.containsKey(wordToLetter)) {
            int quantity = map.get(wordToLetter);
            map.put(wordToLetter, ++quantity);
        } else {
            map.put(wordToLetter, 1);
        }
    }
     return map;
}
英文:

Here is one way to test the characters. It does not use Junit but could be easily adapted.

Random r = new Random();
// save the seed for repeated testing below
long seed = r.nextLong();
r.setSeed(seed);
// supplier to get the next count of letters between 5 and 14 chars
Supplier&lt;Integer&gt; rnd = () -&gt; r.nextInt(10) + 5;

Now generate the test string using the a set of letters.

String letters = &quot;abcdefg&quot;;
// this just concatenates varying lengths of the test characters
String testString = letters.chars()
.mapToObj(ch -&gt; ((char) ch + &quot;&quot;).repeat(rnd.get()))
.collect(Collectors.joining(&quot;&quot;));

Now call your method to get the do the count.

Map&lt;Character, Integer&gt; freq = countChars(testString);

Now perform the test. Re-seed the random number and compare the known counts of the letters to those computed.

r.setSeed(seed);
for (char ch : letters.toCharArray()) {
System.out.printf(&quot;Count for &#39;%s&#39; %s%n&quot;, ch,
(freq.get(ch) == rnd.get()) ? &quot;passes&quot; :
&quot;does not pass&quot;);
}

For counting method it prints

Count for &#39;a&#39; passes
Count for &#39;b&#39; passes
Count for &#39;c&#39; passes
Count for &#39;d&#39; passes
Count for &#39;e&#39; passes
Count for &#39;f&#39; passes
Count for &#39;g&#39; passes

Your code put in a method.

public static Map&lt;Character, Integer&gt; countChars(String string) {
LinkedHashMap&lt;Character, Integer&gt; map = new LinkedHashMap&lt;&gt;();
for (int i = 0; i &lt; string.length(); i++) {
char wordToLetter = string.toLowerCase().charAt(i);
if (map.containsKey(wordToLetter)) {
int quantity = map.get(wordToLetter);
map.put(wordToLetter, ++quantity);
} else {
map.put(wordToLetter, 1);
}
}
return map;
}
</details>
# 答案4
**得分**: 0
```java
public class Test {
public static void main(String[] args) {
String str = "abc de";
Map<Character, Integer> map = stringToMap(str);
Map<Character, Integer> mapTest = stringToMapTest(str);
// 可视化比较
System.out.println(map);      // {a=1, b=1, c=1,  =1, d=1, e=1}
System.out.println(mapTest);  // {a=1, b=1, c=1,  =1, d=1, e=1}
// 自动化比较
System.out.println(map.equals(mapTest));                // true
// 逐步比较
System.out.println(map.getOrDefault('a', 0).equals(1)); // true
System.out.println(map.getOrDefault('b', 0).equals(1)); // true
}
private static Map<Character, Integer> stringToMap(String str) {
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < str.length(); i++) {
char wordToLetter = str.toLowerCase().charAt(i);
if (map.containsKey(wordToLetter)) {
int quantity = map.get(wordToLetter);
map.put(wordToLetter, ++quantity);
} else {
map.put(wordToLetter, 1);
}
}
return map;
}
private static Map<Character, Integer> stringToMapTest(String str) {
return str.chars()
.mapToObj(ch -> (char) ch)
.collect(Collectors.toMap(
ch -> ch,
ch -> 1,
Integer::sum,
LinkedHashMap::new));
}
}
英文:

Approach to testing without JUnit

The way to check a method is to call it from another method and compare results with some verification method or pre-known expected value. In this case, without junit, it might look like this:

public class Test {
    public static void main(String[] args) {
        String str = &quot;abc de&quot;;

        Map&lt;Character, Integer&gt; map = stringToMap(str);
        Map&lt;Character, Integer&gt; mapTest = stringToMapTest(str);

        // visual comparison
        System.out.println(map);      // {a=1, b=1, c=1,  =1, d=1, e=1}
        System.out.println(mapTest);  // {a=1, b=1, c=1,  =1, d=1, e=1}

        // automated comparison
        System.out.println(map.equals(mapTest));                // true

        // step-by-step comparison
        System.out.println(map.getOrDefault(&#39;a&#39;, 0).equals(1)); // true
        System.out.println(map.getOrDefault(&#39;b&#39;, 0).equals(1)); // true
    }

    private static Map&lt;Character, Integer&gt; stringToMap(String str) {
        LinkedHashMap&lt;Character, Integer&gt; map = new LinkedHashMap&lt;&gt;();
        for (int i = 0; i &lt; str.length(); i++) {
            char wordToLetter = str.toLowerCase().charAt(i);
            if (map.containsKey(wordToLetter)) {
                int quantity = map.get(wordToLetter);
                map.put(wordToLetter, ++quantity);
            } else {
                map.put(wordToLetter, 1);
            }
        }
        return map;
    }

    private static Map&lt;Character, Integer&gt; stringToMapTest(String str) {
        return str.chars()
                .mapToObj(ch -&gt; (char) ch)
                .collect(Collectors.toMap(
                        ch -&gt; ch,
                        ch -&gt; 1,
                        Integer::sum,
                        LinkedHashMap::new));
    }
}

huangapple
  • 本文由 发表于 2020年10月11日 21:47:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64304687.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定