简单的 JUnit 测试

Simple JUnit test

我是编程新手,我在 class 开始学习 JUnit。我的任务是测试用户是否输入了正确的数字而不是字母或其他内容。

我的老师给了我主要的class,我只需要编写 JUnit 代码。

主要代码如下:

public class CheckPoint {

    public static String readString(String msg) throws java.io.IOException {

        DataInputStream din = new DataInputStream(System.in);
        System.out.print(msg);
        return din.readLine();

    }

    public static int getNum(char c) throws java.io.IOException {

        int n;
        int indicator = 1;

        for (int i = 0; i < 1; i++) {

            String s = readString("Type a number: ");

            try {

                n = Integer.parseInt(s);
                System.out.println("Invalid number: " + n);

            }

            catch (NumberFormatException nfe) {
                
                System.out.println("Wrong.");
                indicator = 2;

            }

        }

        System.out.println("End.");
        return indicator;

    }

}

这是我在 JUnit 中尝试的 class:

class numericTest {

    @Test
    public void numericTest() {
        
        int n = 50;
        int expectedIndicator = 1;
        
        CheckPoint cp = new CheckPoint(n); //"The constructor CheckPoint(int) is undefined"
        
        int originalIndicator = cp.getNum();
        
        assertEquals(expectedIndicator, originalIndicator); //"The method getNum(char) in the type CheckPoint is not applicable in the arguments ()"
    }

}

我在各自的行中评论了我遇到的错误。

我该怎么办?

以下几点可以帮助您解决问题:

  1. 在你的 CheckPoint class 中没有用输入数字定义的构造函数,这就是编译器给你错误“构造函数 CheckPoint(int) 未定义”的原因。
  2. getNum() 方法需要一个字符作为输入,但您在调用它时没有给出字符输入 cp.getNum();