Java – unit test edge cases using JUnit

I have a utility class called stringprocessor In the breaklongwords () method, zero width spaces will be added to the input as long as the character sequence lacks spaces of predefined length:

public class StringProcessor {

    private static final int WORD_MAX_LENGTH = 40;

    public String breakLongWords(CharSequence input) {
        // add a zero-width space character after a word
        // if its length is greater than WORD_MAX_LENGTH and doesn't have any space in it
    }
}

Static field word_ MAX_ Length is an implementation detail and should not be exposed to other classes (including test classes)

Now, how to access word without_ MAX_ In the case of length, test the edge in JUnit? For example:

@Test
public void breakLongWords_EdgeCase() {
    String brokenText = stringProcessor.breakLongWords
            ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); // its length should be = WORD_MAX_LENGTH 

    assertEquals(41,brokenText.length()); // 41 (WORD_MAX_LENGTH + 1) is also hard-coded here
}

Solution

Usually these fields are "package private" (no access modifier), and unit tests are placed on the same package Therefore, constants are visible for tests and classes from the same package and hidden for other packages

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>