首页 > 解决方案 > 编写一个测试类,测试java.lang.String类中的以下方法:length ,charAt ,substring ,indexOf

问题描述

我不知道如何编写所有这些代码,然后通过 junit 测试对其进行测试。显然,它们需要相当多的方法等。但我不知道从哪里开始,该做什么。任何帮助都将受到极大的欢迎。

标签: javajunit

解决方案


尝试让这段代码在 Java 环境中运行并编辑一些值以了解它在做什么。

public class Main {
    public static void main(String args[]) {
        // Create a String to test with
        String testString = "some test text";

        // Prints out the number of characters in the String
        System.out.println(testString.length());

        // Prints out the character at the index of '2'
        System.out.println(testString.charAt(2));

        // Prints out a new String starting at index '5' and ending at index '9' 
        System.out.println(testString.substring(5, 9));

        // Prints out the index number that the word 'text' starts at
        System.out.println(testString.indexOf("text"));
    }

}

推荐阅读