I'm doing coursework for Uni and I'm really struggling with the final task before I finish:
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.
The task 5 tasks were
- Return an error for no input argument
- Error handling to ensure non-integer inputs are not converted but do not result in a failed build.
Here is the code:
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");
}
And what I have as a Test 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"});
}
}
Now, I know this is wrong, but my brain has turned to soup trying to figure out how to do this and it's due on Friday. I'm not looking for a full solution, just something to push me in the right direction so I can finish myself as I can't find any tutorials covering something similar to this.
CodePudding user response:
According to the task description, the unit tests would look something like the following:
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"});
}
}
If you try this you will notice the first one is failing because you are not throwing an exception in that case. So you have to fix your implementation accordingly.
Additionally, are you sure you want to have all your code in your main()
method? I guess not. Consider defining classes so that you can easily test each one of them.
Finally, I suggest you read some stuff about unit testing to get a better grasp of the concept: