0

I would like to preface by saying I'm well versed with python but only slightly with java and hardly with JUNT

When debugging in python I would normally print out the value that I think could be erroneous how would I do this in java when running the script through JUNIT?

To be more specific I have a method that adds symbols to a map from some string and if they occur more than once the value of the key in the map is incremented.

static Map<Character, Double> getCharFrequancies(String text){
    Map<Character, Double> myMap = new HashMap<Character, Double>();
    int len = (text.length())/2;
    for(int i = text.length() - 1; i>=0; --i) { 
        char symbol = text.charAt(i);
        if(myMap.containsKey(symbol)){
            myMap.put(symbol, myMap.get(symbol)+(1/len));
        }
        else {
            myMap.put(symbol, (double) 1);
        }

    }

    return myMap;
}

And the test script:

public void testGetCharFrequancies() {
    Map<Character,Double> expectedMap = new HashMap<Character,Double>();
    String text = "aa, b ccc.";
    expectedMap.put('a', 2/10.0);
    expectedMap.put(' ', 2/10.0);
    expectedMap.put(',', 1/10.0);
    expectedMap.put('b', 1/10.0);
    expectedMap.put('c', 3/10.0);
    expectedMap.put('.', 1/10.0);

    Map<Character,Double> actualMap = HuffmanTree.getCharFrequancies(text);
    assertEquals(expectedMap.size(), actualMap.size());
    assertEquals(expectedMap.keySet(), actualMap.keySet());
    for(Character c:expectedMap.keySet()){
        assertEquals(expectedMap.get(c), actualMap.get(c), 0.000000000001);

The Fail is happening at assertEquals(expectedMap.get(c), actualMap.get(c), 0.000000000001); so I want to print out the values of the map. How would I do this?

ps. I'm using eclipse oxygen

7
  • 3
    I wouldn't add a print statement - a spin through the debugger in Eclipse will tell you faster. I'm guessing that your tolerance for comparison of the two double values is too small. 1e-12? Too small. Try 1e-3 and progressively make it smaller until you fail. Or maintain actual word counts as integers and forget about frequencies. One more thing: it's spelled "frequencies". Commented Aug 13, 2017 at 22:49
  • So why is this tagged python? Commented Aug 13, 2017 at 22:51
  • @duffymo what is 'tolerance for comparison'? thanks for spotting the spelling, dyslexia is a bitch Commented Aug 13, 2017 at 22:53
  • 2
    No worries. The tolerance is the third parameter in the call to assertEquals. You can't compare two doubles and expect them to match; the best you can do is compare the absolute value of their difference to a tolerance value. That's what the JUnit test framework is doing for you. Commented Aug 13, 2017 at 22:54
  • 1
    I'd put it at that line in the JUnit code to find out what those values you're comparing are. If I was surprised in any way at what I saw I'd add another breakpoint in the class that did the calculation until I understood what was going on perfectly. Commented Aug 13, 2017 at 23:25

1 Answer 1

1

I'd recommend that you write it as shown below in the method getCharFrequencies. It'll be good to become familiar with the new lambdas in JDK 8

package utils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author Michael
 * @link https://stackoverflow.com/questions/41006856/how-do-i-catch-a-nosuchelementexception?noredirect=1#comment69222264_41006856
 */
public class StringUtils {

    private StringUtils() {}

    public static List<String> tokenize(String str) {
        String [] tokens = new String[0];
        if (isNotBlankOrNull(str)) {
            str = str.trim();
            tokens = str.split("\\s+");
        }
        return Arrays.asList(tokens);
    }

    public static boolean isBlankOrNull(String s) {
        return ((s == null) || (s.trim().length() == 0));
    }

    public static boolean isNotBlankOrNull(String s) {
        return !isBlankOrNull(s);
    }

    public static boolean hasSufficientTokens(int numTokens, String str) {
        return (numTokens >= 0) && tokenize(str).size() >= numTokens;
    }

    public static Map<String, Long> getCharFrequencies(String text) {
        Map<String, Long> charFrequencies = new TreeMap<>();
        if (isNotBlankOrNull(text)) {
            // https://stackoverflow.com/questions/4363665/hashmap-implementation-to-count-the-occurences-of-each-character
            charFrequencies = Arrays.stream(text.split("")).collect(Collectors.groupingBy(c -> c, Collectors.counting()));
        }
        return charFrequencies;
    }
}

Here's the JUnit test to prove that it works:

package utils;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by Michael
 * Creation date 12/6/2016.
 * @link https://stackoverflow.com/questions/41006856/how-do-i-catch-a-nosuchelementexception?noredirect=1#comment69222264_41006856
 */
public class StringUtilsTest {

    @Test
    public void testIsNotBlankOrNull_NullString() {
        Assert.assertFalse(StringUtils.isNotBlankOrNull(null));
    }

    @Test
    public void testIsNotBlankOrNull_EmptyString() {
        Assert.assertFalse(StringUtils.isNotBlankOrNull(""));
    }

    @Test
    public void testIsNotBlankOrNull_BlankString() {
        Assert.assertFalse(StringUtils.isNotBlankOrNull("        "));
    }

    @Test
    public void testIsNotBlankOrNull_FullString() {
        Assert.assertTrue(StringUtils.isNotBlankOrNull("I'm not null, blank, or empty"));
    }

    @Test
    public void testTokenize_NullString() {
        // setup
        List<String> expected = Collections.EMPTY_LIST;
        // exercise
        List<String> actual = StringUtils.tokenize(null);
        // assert
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void testTokenize_EmptyString() {
        // setup
        List<String> expected = Collections.EMPTY_LIST;
        // exercise
        List<String> actual = StringUtils.tokenize("");
        // assert
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void testTokenize_BlankString() {
        // setup
        List<String> expected = Collections.EMPTY_LIST;
        // exercise
        List<String> actual = StringUtils.tokenize("        ");
        // assert
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void testTokenize_FullString() {
        // setup
        List<String> expected = Arrays.asList("I'm", "not", "null,", "blank,", "or", "empty");
        // exercise
        List<String> actual = StringUtils.tokenize("    I'm not     null,    blank, or empty    ");
        // assert
        Assert.assertEquals(expected.size(), actual.size());
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void hasSufficientTokens_NegativeTokens() {
        // setup
        int numTokens = -1;
        String str = "    I'm not     null,    blank, or empty    ";
        // exercise
        // assert
        Assert.assertFalse(StringUtils.hasSufficientTokens(numTokens, str));
    }

    @Test
    public void hasSufficientTokens_InsufficientTokens() {
        // setup
        String str = "    I'm not     null,    blank, or empty    ";
        int numTokens = StringUtils.tokenize(str).size() + 1;
        // exercise
        // assert
        Assert.assertFalse(StringUtils.hasSufficientTokens(numTokens, str));
    }

    @Test
    public void hasSufficientTokens_NullString() {
        // setup
        String str = "";
        int numTokens = StringUtils.tokenize(str).size();
        // exercise
        // assert
        Assert.assertTrue(StringUtils.hasSufficientTokens(numTokens, str));
    }

    @Test
    public void hasSufficientTokens_Success() {
        // setup
        String str = "    I'm not     null,    blank, or empty    ";
        int numTokens = StringUtils.tokenize(str).size();
        // exercise
        // assert
        Assert.assertTrue(StringUtils.hasSufficientTokens(numTokens, str));
    }

    @Test
    public void testGetCharFrequencies_NullText() {
        // setup
        String text = null;
        Map<String, Long> expected = new TreeMap<>();
        // exercise
        Map<String, Long> actual = StringUtils.getCharFrequencies(text);
        // assert
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void testGetCharFrequencies_BlankText() {
        // setup
        String text = "        ";
        Map<String, Long> expected = new TreeMap<>();
        // exercise
        Map<String, Long> actual = StringUtils.getCharFrequencies(text);
        // assert
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void testGetCharFrequencies_Success() {
        // setup
        String text = "The quick brown fox jumped over the lazy dog!        ";
        String expectedString = "{T=1,  =16, !=1, a=1, b=1, c=1, d=2, e=4, f=1, g=1, h=2, i=1, j=1, k=1, l=1, m=1, n=1, o=4, p=1, q=1, r=2, t=1, u=2, v=1, w=1, x=1, y=1, z=1}";
        // exercise
        Map<String, Long> actual = StringUtils.getCharFrequencies(text);
        // assert
        Assert.assertEquals(expectedString, actual.toString());
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.