我是新來的Stackoverflow,我想知道爲什麼幾乎每個人都用一個靜態main()和第一個答案輸出樣本代碼:some ugly main爲什麼你用main()和輸出代替JUnit測試編寫示例代碼
一些醜陋主:
但你張貼看起來它只是一個屬性文件。試試這個:
import java.io.FileInputStream; import java.util.Properties; public class Main { public static void main(String[] args) throws Exception { Properties properties = new Properties(); properties.load(new FileInputStream("test.properties")); System.out.println(properties.getProperty("ReferenceDataLocation")); System.out.println(properties.getProperty("LicenseKey")); System.out.println(properties.getProperty("foo")); } }
,它將打印:
as al null
豈不是更好的把它寫的JUnit測試?它更容易閱讀。您可以使用CTRL + C + CTRL-V + RunAs - > JUnit來驗證結果,並查看預期結果(或不結果)。
我對這個想法有錯嗎?
我會寫的主要是這樣的:
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import java.io.ByteArrayInputStream;
import java.util.Properties;
import org.junit.Test;
public class TestSomeInputStreamAsProperties {
String someFileAsString =
"ReferenceDataLocation = as\n"+
" \n" +
" \n" +
" ##############################################################################\n" +
" #\n" +
" # LicenseKey\n" +
" # Address Doctor License\n" +
" #\n" +
" ##############################################################################\n" +
" LicenseKey = al\n";
@Test
public void whenReadingFromSomeInputStreamWeShouldGetProperties() throws Exception {
// Arrange
Properties properties = new Properties();
// Act
properties.load(new ByteArrayInputStream(someFileAsString.getBytes()));
// Assert
assertThat(properties.getProperty("ReferenceDataLocation"), is("as"));
assertThat(properties.getProperty("LicenseKey"), is("al"));
assertThat(properties.getProperty("foo"), is(nullValue()));
}
}
的問題是:爲什麼我會寫與main()和輸出的樣本?爲什麼用戶不試圖登陸JUnit列車並開始編寫測試來驗證他們的代碼?
+
另一個問題:爲什麼沒有人發表自己的JUnit測試的問題?
我有點失望。
編輯: - 不要誤解我的意思。這只是期望>現實;)我認爲stackoverflow仍然是一個很棒的網站,我會在這裏寫下我所有的問題,並試圖幫助別人解決他們的問題。我認爲,JUnit更加普及,您的社區應該重視解決JUnit問題。
相反,我意識到它不是想要的。 你也不會失望嗎?
這是一個社區網站,因此而不是失望,爲什麼不作出貢獻,並做改變的事情?另外,它真的有很大的不同嗎?這裏要問的很大一部分問題是學生和那些沒有太多經驗的人,他們可能不知道JUnit或者它在測試之外的用途。 – spikeheap
這是我的想法,這就是爲什麼我問這個問題。我開始用JUnit測試回答問題,自己寫UnitTests作爲問題,我很樂意將JUnit傳播到世界上,讓它成爲更好的地方。 – MartinL