如何修复这些单元测试?

How do I fix these Unit Tests?

我正在为 Uni 做课程作业,在完成之前我真的很难完成最后的任务:

Using any appropriate method (Bash scripts, JUnit, Maven, Gradle etc.) implement a set of unit tests which confirm that the requirements in Task 5 have been met. These tests should be executed automatically by Jenkins as part of a single job which runs all tests and results in a failed job ONLY if any of the tests DO NOT pass. Proportionate marks will be awarded for partial solutions.

该任务共5个任务

  1. Return 没有输入参数的错误
  2. 错误处理以确保不转换非整数输入但不会导致构建失败。

代码如下:

class Dec2Hex {

    public static int Arg1;

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.print("No input detected. Try Again.\n");
            return;
        }



        try {
            Arg1 = Integer.parseInt(args[0]);
            //parseInt succeeded
        } catch(NumberFormatException e)
        {
            //parseInt failed
        }

        if (Arg1 <= 0) {
            System.out.println("Value must be a positive Int");
            return;
        }

        char ch[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int rem, num;
        num = Arg1;
        String hexadecimal = "";
        System.out.println("Converting the Decimal Value " + num + " to Hex...");

        while (num != 0) {
            rem = num % 16;
            hexadecimal = ch[rem] + hexadecimal;
            num = num / 16;
        }

        System.out.println("Hexadecimal representation is: " + hexadecimal);
        System.out.println("Ending Program");

    }

以及我的测试 Class:

import static org.junit.jupiter.api.Assertions.*;

class Dec2HexTest {

    @org.junit.jupiter.api.Test
    void main() {
        Dec2Hex.main(new String[] {"16"});
        Dec2Hex.main(new String[] {"641"});
        Dec2Hex.main(new String[] {"16541"});
        Dec2Hex.main(new String[] {"asdasd"});
    }
}

现在,我 知道 这是错误的,但我的大脑已经变成汤,试图弄清楚如何做到这一点,它将于周五到期。我不是在寻找一个完整的解决方案,只是想把我推向正确的方向,这样我就可以完成自己的工作,因为我找不到任何涵盖与此类似内容的教程。

根据任务描述,单元测试如下所示:

import static org.junit.jupiter.api.Assertions.assertThrows;

public class MainTest {

    @org.junit.jupiter.api.Test
    public void shouldThrowException_GivenNoInputArgument() {
        assertThrows(Exception.class, () -> {
            Main.main(new String[] {});
        });
    }

    @org.junit.jupiter.api.Test
    public void shouldNotThrowException_GivenNonIntegerArgument() {
        Main.main(new String[] {"non-integer-argument"});
    }

}

如果您尝试此操作,您会注意到第一个失败,因为在那种情况下您没有抛出异常。所以你必须相应地修复你的实现。

此外,您确定要将所有代码都放在 main() 方法中吗?我猜不会。考虑定义 类 以便您可以轻松地测试它们中的每一个。

最后,我建议您阅读一些有关单元测试的资料,以便更好地掌握概念:

  1. https://www.manning.com/books/unit-testing
  2. https://betterprogramming.pub/13-tips-for-writing-useful-unit-tests-ca20706b5368
  3. https://www.baeldung.com/junit-5