为什么要使用main()和输出而不是JUnit Tests编写示例代码

Mar*_*inL 1 java junit program-entry-point

我是Stackoverflow的新手,我想知道,为什么几乎每个人都用静态main()编写样本代码并在第一个答案中输出如下:一些丑陋的主要内容

从一些丑陋的主要:

但你发布的内容看起来就像是一个属性文件.试试这个:

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")); 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

将打印:

as
al
null
Run Code Online (Sandbox Code Playgroud)

把它写成JUnit Test不是更好吗?它更容易阅读.您可以使用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()));
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是:为什么我要用main()和输出写一个样本?为什么用户不试图登上JUnit列车并开始编写测试来验证他们的代码?

+

另一个问题:人们为什么不将他们的问题发布为JUnit测试?

我有点失望.

编辑: - 不要误会我的意思.这只是期望>现实;)我认为stackoverflow仍然是一个伟大的网站,我会在这里写下我所有的问题,并试图帮助其他人解决他们的问题.我认为,JUnit更具传播性,您的社区将非常感谢您专注于使用JUnit解决问题.

相反,我意识到它不是通缉.你也不会失望吗?

Gre*_*ill 5

不是每个人都有JUnit,所以一个简单的程序main()更有可能在任何地方运行.