[英]Pass command line arguments to JUnit test case being run programmatically
[英]How to pass command line arguments to Junit Test
我有一個接受命令行參數的主類,並且正在將此參數傳遞給另一個類。 現在,我必須使用參數測試myClass。 我有JUnit對其進行測試,但我想知道如何在測試中通過
public class JsonFileTest {
public static void main(String[] fileNames) {
myClass class = new myClass(fileNames);
}
}
我是JUnit的初學者,正在學習它,因此,如果有任何指導,我們將不勝感激。 我需要將文件名傳遞給類方法。
您想要以這種方式參數化單元測試似乎違反直覺。 我建議您考慮一些參數,並在單元測試中對其進行硬編碼。 這樣,它們是可重復的,並有望提供良好的覆蓋范圍。
對初學者有用的幾點:
您無法在Java中將對象命名為“類”。
建議遵循Java命名約定,因此類名應以大寫字母開頭。
現在,關於命令行參數。 您的代碼中有一個答案:
public static void main(String[] fileNames) {
String[] fileNames
是命令行參數的數組。
因此,要為您的方法提供一些參數,請使用所需的參數對其進行初始化。
就像是:
@Test
public void testMainMethod(){
JsonFileTest.main(new String[]{"file1", "file2"});
}
但是在現實生活中,測試主要方法並不是一個好主意。 它不返回任何內容,因此您只能創建一些測試來檢查它是否引發了異常。 這個想法是測試整個邏輯。 在此示例情況下,對象構造:
@Test
public void testConstructor(){
myClass class = new myClass(new String[]{"file1", "file2"});
/* Your assertions here */
}
您無需將命令行參數傳遞給JUnit執行。 相反,您的測試方法應該構建/准備所有內容,並使用原始程序在使用命令行參數時將要執行的參數來調用new myClass(...)
構造函數。 代碼可能看起來像這樣:
@Test
public void checkForWhatever() {
// prepare everything here like create a temp file
File x = ...;
String filename = x.getName(); // or maybe even x.getAbsolutePath();
String[] arguments = new String[1];
arguments[0] = filename;
// now call your constructor
myClass obj = new myClass(arguments);
// do any checks here now
Assertions.assertTrue(obj.getWhatever());
// ...
}
我想將參數傳遞給@BeforeAll方法以創建缺少的目錄。
多個項目依賴於這些目錄,但是項目位於不同的位置:
我想將文件路徑作為變量傳遞給JUnit方法,以便它可以在每個項目的內部創建Log,Temp,Input等。 如何使用cli做到這一點? 我試過了:
java -jar junit-platform-console-standalone-1.5.2.jar --class-path out --scan-class-path "C:\Workspace\Project1"
另外,我有一個帶有參數的構造函數:
public class ConnectIntegrationTest {
private String workspace;
public ConnectIntegrationTest(String localWorkspace) {
this.workspace = localWorkspace;
}
@BeforeAll
void setupMissingDirectories() throws Exception {
我一定在這里想念什么...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.