如何测试LinkedHashMap的值和键? [英] How to test values and keys of LinkedHashMap?

查看:107
本文介绍了如何测试LinkedHashMap的值和键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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<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.

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

推荐答案

下面给出的是一种测试方法:

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<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异常.

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

这篇关于如何测试LinkedHashMap的值和键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆