我正在為 Uni 做課程,但在完成之前我真的在為最后的任務而苦苦掙扎:
使用任何適當的方法(Bash 腳本、JUnit、Maven、Gradle 等)實施一組單元測驗,以確認已滿足任務 5 中的要求。這些測驗應由 Jenkins 作為單個作業的一部分自動執行,該作業運行所有測驗并僅在任何測驗未通過時才會導致作業失敗。部分解決方案將給予相應的分數。
任務 5 個任務是
- 沒有輸入引數時回傳錯誤
- 錯誤處理以確保非整數輸入不會被轉換但不會導致構建失敗。
這是代碼:
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");
}
我作為測驗班所擁有的:
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.
uj5u.com熱心網友回復:
根據任務描述,單元測驗將類似于以下內容:
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()方法中包含所有代碼嗎?我猜不是。考慮定義類,以便您可以輕松地測驗每個類。
最后,我建議您閱讀一些有關單元測驗的內容以更好地理解這個概念:
- https://www.manning.com/books/unit-testing
- https://betterprogramming.pub/13-tips-for-writing-useful-unit-tests-ca20706b5368
- https://www.baeldung.com/junit-5
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/350653.html
